Java数组操作的十大方法

【Java数组操作的十大方法】原文请戳这里 Top 10 Methods for Java Arrays
0.定义数组

String[] aArray = new String[5]; String[] bArray = {"a","b","c", "d", "e"}; String[] cArray = new String[]{"a","b","c","d","e"};

1.在Java中打印一个数组
int[] intArray = { 1, 2, 3, 4, 5 }; String intArrayString = Arrays.toString(intArray); // 直接打印将打印地址引用 System.out.println(intArray); // [I@7150bd4dSystem.out.println(intArrayString); // [1, 2, 3, 4, 5]

2. 用一个数组创建一个ArrayList
String[] stringArray = { "a", "b", "c", "d", "e" }; ArrayList arrayList = new ArrayList(Arrays.asList(stringArray)); System.out.println(arrayList); // [a, b, c, d, e]

3.检查数组中是否包含某个确认的值
String[] stringArray = { "a", "b", "c", "d", "e" }; boolean b = Arrays.asList(stringArray).contains("a"); System.out.println(b); // true

4.连接两个数组
int[] intArray = { 1, 2, 3, 4, 5 }; int[] intArray2 = { 6, 7, 8, 9, 10 }; // Apache Commons Lang library int[] combinedIntArray = ArrayUtils.addAll(intArray, intArray2);

5. 声明一个内联数组
method(new String[]{"a", "b", "c", "d", "e"});

6. 将提供给数组的元素,连接成一个字符串
// containing the provided list of elements // Apache common lang String j = StringUtils.join(new String[] { "a", "b", "c" }, ", "); System.out.println(j); // a, b, c

7. 将一个ArrayList 转换为一个Array
String[] stringArray = { "a", "b", "c", "d", "e" }; ArrayList arrayList = new ArrayList(Arrays.asList(stringArray)); String[] stringArr = new String[arrayList.size()]; arrayList.toArray(stringArr); for (String s : stringArr) System.out.println(s);

8.将一个array转换为一个set
Set set = new HashSet(Arrays.asList(stringArray)); System.out.println(set);

9.反转一个数组
int[] intArray = { 1, 2, 3, 4, 5 }; ArrayUtils.reverse(intArray); System.out.println(Arrays.toString(intArray)); //[5, 4, 3, 2, 1]

10.移除数组中的一个元素
int[] intArray = { 1, 2, 3, 4, 5 }; int[] removed = ArrayUtils.removeElement(intArray, 3); //create a new array System.out.println(Arrays.toString(removed));

补充一个: int数组转换为byte数组
byte[] bytes = ByteBuffer.allocate(4).putInt(8).array(); for (byte t : bytes) { System.out.format("0x%x ", t); }

    推荐阅读