Java数组常用方法

数组基础:http://www.cnblogs.com/mengdd/archive/2013/01/04/2844264.html

import java.util.Arrays;

1):创建数组

1 String[] a = new String[5]; 
2 String[] b = {"a","b","c", "d", "e"}; 
3 String[] c = new String[]{"a","b","c","d","e"};

2):输出数组

 1 import java.util.*; 
 2 class js 
 3 { 
 4     public static void main(String[] args) 
 5     { 
 6         int[] a = { 1, 2, 3, 4, 5 }; 
 7         String b = Arrays.toString(a);
 8 
 9         // print directly will print reference value 
10         System.out.println(a); 
11         // [I@7150bd4d
12 
13         System.out.println(b); 
14         // [1, 2, 3, 4, 5] 
15     } 
16 }

3):从一个数组创建数组列表

1 String[] a = { "a", "b", "c", "d", "e" };
2 ArrayList<String> List = new ArrayList<String>(Arrays.asList(a));
3 System.out.println(List);
4 // [a, b, c, d, e]

4):检查一个数组是否包含某个值

1 String[] stringArray = { "a", "b", "c", "d", "e" };
2 boolean b = Arrays.asList(stringArray).contains("a");
3 System.out.println(b);
4 // true

5):连接两个数组

 1 int[] a = { 1, 2, 3, 4, 5 }; 2 int[] b = { 6, 7, 8, 9, 10 }; 3 int[] c = ArrayUtils.addAll(a,b); 

6):声明一个内联数组

 1 method(new String[]{"a", "b", "c", "d", "e"}); 

7):把提供的一个数组放入字符串

 1 String j = StringUtils.join(new String[] { "a", "b", "c" }, ", "); 2 System.out.println(j); 3 // a, b, c 

8):将一个数组列表转化为数组

1 String[] a = { "a", "b", "c", "d", "e" };
2 ArrayList<String> aList = new ArrayList<String>(Arrays.asList(a));
3 String[] b = new String[aList.size()];
4 aList.toArray(b);
5 for (String s : b)
6     System.out.println(s);

9):将一个数组转化为集(set)

 1 Set<String> set = new HashSet<String>(Arrays.asList(stringArray)); 2 System.out.println(set); 3 //[d, e, b, c, a] 

10):逆向一个数组

1 int[] intArray = { 1, 2, 3, 4, 5 };
2 ArrayUtils.reverse(intArray);
3 System.out.println(Arrays.toString(intArray));
4 //[5, 4, 3, 2, 1]

11):移除数组中的元素

1 int[] intArray = { 1, 2, 3, 4, 5 };
2 int[] removed = ArrayUtils.removeElement(intArray, 3);//create a new array
3 System.out.println(Arrays.toString(removed));

12):将整数转换为字节数组

1 byte[] bytes = ByteBuffer.allocate(4).putInt(8).array();
2 for (byte t : bytes) {
3    System.out.format("0x%x ", t);
4 }
原文地址:https://www.cnblogs.com/qq188380780/p/6609997.html