JavaRush /Java Blog /Random-TW /Java 中 10 種常用的陣列技術
theGrass
等級 24
Саратов

Java 中 10 種常用的陣列技術

在 Random-TW 群組發布
Java 中常用的陣列 技術有以下 10 種。他們在 Stack Overflow(一個關於程式設計的問答系統)上排名最高。 Java 中 10 種常用的陣列技術 - 1
  1. 數組聲明

    String[] aArray = new String[5];
    String[] bArray = {"a","b","c", "d", "e"};
    String[] cArray = new String[]{"a","b","c","d","e"};
  2. 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]
  3. 從數組建立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]
  4. 檢查數組中的特定值

    String[] stringArray = { "a", "b", "c", "d", "e" };
    boolean b = Arrays.asList(stringArray).contains("a");
    System.out.println(b);
    // true
  5. 合併兩個數組

    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. 在一行中聲明一個數組

    method(new String[]{"a", "b", "c", "d", "e"});
  7. 將數組元素連接成字串

    // 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. 轉換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);
  9. 將陣列轉換為集合 ( Set)

    Set<String> set = new HashSet<String>(Arrays.asList(stringArray));
    System.out.println(set);
    //[d, e, b, c, a]
  10. 傳回一個數組,其中元素的順序相反

    int[] intArray = { 1, 2, 3, 4, 5 };
    ArrayUtils.reverse(intArray);
    System.out.println(Arrays.toString(intArray));
    //[5, 4, 3, 2, 1]
  11. 從數組中刪除一個元素

    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 個位元組並放入數字int8,然後將所有這些 (0, 0, 0, 8) 轉換為數組byte使用呼叫的array()

    byte[] bytes = ByteBuffer.allocate(4).putInt(8).array();
    
    for (byte t : bytes) {
       System.out.format("0x%x ", t);
    }
留言
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION