數組是 Java 最基礎的容器,JDK 在 java.lang.System 和 java.util.Arrays 中提供了高性能的原生操作方法。本文通過實例速查三大高頻場景:複製、排序、比較。
System.arraycopypublic static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
src:源數組srcPos:源起始索引dest:目標數組(必須預先分配足夠空間)destPos:目標起始索引length:複製元素個數int[] src = {1, 2, 3, 4, 5};
int[] dest = new int[8]; // {0,0,0,0,0,0,0,0}
System.arraycopy(src, 0, dest, 0, 3);
// dest → {1, 2, 3, 0, 0, 0, 0, 0}
// 覆蓋中間段
System.arraycopy(src, 1, dest, 2, 2);
// dest → {1, 2, 2, 3, 0, 0, 0, 0}
JVM 內部實現為本地方法(通常映射到 memmove),比手寫循環快 10-100 倍,且自動處理數組重疊複製(如將數組前移一位)。
Arrays.sortsort(int[] a) / sort(Object[] a):全量排序sort(int[] a, int fromIndex, int toIndex):區間排序sort(T[] a, Comparator<? super T> c):自定義比較器int[] arr = {2, 9, 3, 6, 7, 4};
Arrays.sort(arr); // → {2, 3, 4, 6, 7, 9}
// 降序:基本類型無直接支持,需轉包裝類或手寫
Integer[] boxed = Arrays.stream(arr).boxed().toArray(Integer[]::new);
Arrays.sort(boxed, Collections.reverseOrder());
Arrays.equals / Arrays.deepEqualsequals==(基本類型)或 equals()(對象)返回 true。int[] a = {1, 2};
int[] b = {1, 2};
Arrays.equals(a, b); // true
deepEqualsObject[] oa = {new int[]{1,2}, "str"};
Object[] ob = {new int[]{1,2}, "str"};
Arrays.equals(oa, ob); // false(引用不同)
Arrays.deepEquals(oa, ob); // true
| 誤區 | 正確做法 |
|---|---|
int[] b = a; 以為複製了數組 |
僅複製引用,修改 b 影響 a。需用 Arrays.copyOf 或 arraycopy |
| 對象數組排序不指定 Comparator | 元素必須實現 Comparable,否則拋 ClassCastException |
多維數組用 Arrays.equals |
必須用 Arrays.deepEquals |
| 並發環境下直接排序共享數組 | 先複製快照 Arrays.copyOf,或使用 CopyOnWriteArrayList |
Arrays.stream(arr).sorted().toArray():函數式風格,自動裝箱基本類型,適合鏈式操作。IntStream.of(arr).sorted().toArray():避免裝箱開銷,性能更接近原生 Arrays.sort。List 比較可用 List.equals(逐元素調用 Arrays.equals)。System.arraycopy 是底層複製利器,Arrays.sort 提供工業級排序,Arrays.equals/deepEquals 覆蓋淺/深比較需求。熟練掌握這三組 API,配合 Java 8 Stream 增強,能優雅高效地解決 90% 數組操作場景。