-
數組聲明
String[] aArray = new String[5]; String[] bArray = {"a","b","c", "d", "e"}; String[] cArray = new String[]{"a","b","c","d","e"};
-
Java中的數組輸出
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]
-
從數組建立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]
-
檢查數組中的特定值
String[] stringArray = { "a", "b", "c", "d", "e" }; boolean b = Arrays.asList(stringArray).contains("a"); System.out.println(b); // true
-
合併兩個數組
int[] intArray = { 1, 2, 3, 4, 5 }; int[] intArray2 = { 6, 7, 8, 9, 10 }; // Apache Commons Lang library int[] combinedIntArray = ArrayUtils.addAll(intArray, intArray2);
-
在一行中聲明一個數組
method(new String[]{"a", "b", "c", "d", "e"});
-
將數組元素連接成字串
// 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
-
轉換
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);
-
將陣列轉換為集合 (
Set
)Set<String> set = new HashSet<String>(Arrays.asList(stringArray)); System.out.println(set); //[d, e, b, c, a]
-
傳回一個數組,其中元素的順序相反
int[] intArray = { 1, 2, 3, 4, 5 }; ArrayUtils.reverse(intArray); System.out.println(Arrays.toString(intArray)); //[5, 4, 3, 2, 1]
-
從數組中刪除一個元素
int[] intArray = { 1, 2, 3, 4, 5 }; int[] removed = ArrayUtils.removeElement(intArray, 3);//create a new array System.out.println(Arrays.toString(removed));
還有一件事 -
byte
基於類型的值創建一個類型的數組int
(大約ByteBuffer
,選擇其中的 4 個位元組並放入數字int
8,然後將所有這些 (0, 0, 0, 8) 轉換為數組byte
使用呼叫的array()
)byte[] bytes = ByteBuffer.allocate(4).putInt(8).array(); for (byte t : bytes) { System.out.format("0x%x ", t); }
Java 中 10 種常用的陣列技術
Java 中常用的陣列 技術有以下 10 種。他們在 Stack Overflow(一個關於程式設計的問答系統)上排名最高。
GO TO FULL VERSION