1. 程式人生 > >陣列的10個常用方法

陣列的10個常用方法

以下是Java陣列中最常用的10種方法,它們是 stackoverflow 中投票最多的問題。

0. 宣告陣列

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

1. 列印陣列

int[] intArray = { 1, 2, 3, 4, 5 };
String intArrayString = Arrays.toString(intArray);
 
// print directly will print reference value
System.out.println(intArray); // [[email protected] System.out.println(intArrayString); // [1, 2, 3, 4, 5]

2. 從陣列建立一個 ArrayList

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. 檢查陣列是否包含某一個值

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 轉換成陣列

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

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

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[] bytes = ByteBuffer.allocate(4).putInt(8).array();
 
for (byte t : bytes) {
   System.out.format("0x%x ", t);
}