(译)Java - 数组的10个常用方法


以下是Java数组中最常用的10种方法,它们是 stackoverflow 中投票最多的问题。

0. 声明数组

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

1. 打印数组

1
2
3
4
5
6
7
8
9
int[] intArray = { 1, 2, 3, 4, 5 };
String intArrayString = Arrays.toString(intArray);

// print directly will print reference value
System.out.println(intArray);
// [I@7150bd4d

System.out.println(intArrayString);
// [1, 2, 3, 4, 5]

2. 从数组创建一个 ArrayList

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

3. 检查数组是否包含某一个值

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

4. 合并数组

1
2
3
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. 一行代码声明数组

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

6. 把数组中的元素用指定的分隔符连接起来

1
2
3
4
5
// 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 转换成数组

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

8. 把一个数组转换成 Set

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

9. 反转数组

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

10. 移除数组中的元素

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

附加的方法 - 把 int 转换成字节数组

1
2
3
4
5
byte[] bytes = ByteBuffer.allocate(4).putInt(8).array();

for (byte t : bytes) {
System.out.format("0x%x ", t);
}

版权声明:本文为译文,请尊重原作者,转载请保留原文链接:https://www.programcreek.com/2013/09/top-10-methods-for-java-arrays/