java中的數組
阿新 • • 發佈:2017-07-15
eat position true val apach tin bottom courier ans
Java代碼
2. 輸出一個數組
Java代碼
3. 從一個數組創建數組列表
Java代碼
4. 檢查一個數組是否包含某個值
Java代碼
5. 連接兩個數組
Java代碼
6. 聲明一個內聯數組(Array inline)
Java代碼
7. 把提供的數組元素放入一個字符串
Java代碼
8. 將一個數組列表轉換為數組
Java代碼
9. 將一個數組轉換為集(set)
Java代碼
10. 逆向一個數組
Java代碼
11. 移除數組中的元素
Java代碼
12. 將整數轉換為字節數組
Java代碼
註:本章節是網上查找保存學習使用!
java中數組的定義:
字符串數組:
1、String[] str=new String[5];
2、String[] str=new String[]{"a","b"};
3、String[] str={"a","b"};
整形數組:
1、int[] i=new int[5];
2、int[] i=new int[]{0,1};
3、int[] i={0,1};
其他數組定義的方法類似!
. 聲明一個數組
Java代碼
- String[] aArray = new String[5];
- String[] bArray = {"a","b","c", "d", "e"};
- String[] cArray = new
2. 輸出一個數組
Java代碼
- 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]
3. 從一個數組創建數組列表
Java代碼
- 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]
4. 檢查一個數組是否包含某個值
Java代碼
- String[] stringArray = { "a", "b", "c", "d", "e" };
- boolean b = Arrays.asList(stringArray).contains("a");
- System.out.println(b);
- // true
5. 連接兩個數組
Java代碼
- int[] intArray = { 1, 2, 3, 4, 5 };
- int[] intArray2 = { 6, 7, 8, 9, 10 };
- // Apache Commons Lang library
- int[] combinedIntArray = ArrayUtils.addAll(intArray, intArray2);
6. 聲明一個內聯數組(Array inline)
Java代碼
- method(new String[]{"a", "b", "c", "d", "e"});
7. 把提供的數組元素放入一個字符串
Java代碼
- // 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
8. 將一個數組列表轉換為數組
Java代碼
- 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);
9. 將一個數組轉換為集(set)
Java代碼
- Set<String> set = new HashSet<String>(Arrays.asList(stringArray));
- System.out.println(set);
- //[d, e, b, c, a]
10. 逆向一個數組
Java代碼
- int[] intArray = { 1, 2, 3, 4, 5 };
- ArrayUtils.reverse(intArray);
- System.out.println(Arrays.toString(intArray));
- //[5, 4, 3, 2, 1]
11. 移除數組中的元素
Java代碼
- int[] intArray = { 1, 2, 3, 4, 5 };
- int[] removed = ArrayUtils.removeElement(intArray, 3);//create a new array
- System.out.println(Arrays.toString(removed));
12. 將整數轉換為字節數組
Java代碼
- byte[] bytes = ByteBuffer.allocate(4).putInt(8).array();
- for (byte t : bytes) {
- System.out.format("0x%x ", t);
- }
java中的數組