| 維度 | 數組 | 容器 |
|---|---|---|
| 效能 | 最高(連續記憶體、直接索引) | 略低(封裝層、動態擴容) |
| 類型安全 | 編譯期強類型 | 泛型擦除,運行期無類型 |
| 基本類型 | 直接存儲 int[] 等 | 需自動裝箱 Integer |
| 長度 | 固定不可變 | 動態擴容 |
**建議**:現代 Java 優先用容器;證明效能瓶頸在數組時再重構。
// 靜態初始化
int[] a1 = new int[5];
int[] a2 = new int[]{1,2,3,4};
int[] a3 = {1,2,3,4}; // 僅聲明處可用
// 動態初始化
int[] a4;
a4 = new int[10];
// 多維數組(必須給第一維長度)
int[][] m1 = new int[3][];
int[][] m2 = new int[][]{{1,2},{3,4,5}};
int[][][] m3 = new int[][][]{{{1,2},{3,4}}};
// 自定義類型數組
Dummy[] objs = {new Dummy(), new Dummy()};
Dummy[] objs2 = new Dummy[5]; // 元素預設 null,需逐個 new
array.length(屬性,非方法)獲取**分配長度**,而非有效元素數。length 僅返回第一維長度。String.length()(方法)。| 方式 | 語法 | 特點 |
|---|---|---|
| for 循環 | 手動逐元素賦值 | 靈活、效能最低 |
| clone() | arr.clone() | 淺拷貝、整體複製、不可指定範圍 |
| System.arraycopy() | System.arraycopy(src, srcPos, dest, destPos, len) | **原生優化、最快**、支援區間、基本/引用類型通用 |
int[] src = {0,1,2,3,4,5,6};
int[] dest = new int[7];
System.arraycopy(src, 0, dest, 3, 3);
// dest → {0,0,0,0,1,2,6}
// 自我覆蓋移動
System.arraycopy(src, 0, src, 3, 3);
// src → {0,1,2,0,1,2,6}
注意:arraycopy 不自動裝箱/拆箱,源目類型必須兼容。
// 一維
Arrays.equals(int[], int[]); // 長度+對應元素皆等
// 多維
Arrays.deepEquals(Object[][], Object[][]); // 遞歸深度比較
Arrays.sort():基本類型雙軸快排,對象穩定歸並排序(需 Comparable 或 Comparator)。Arrays.binarySearch():**前提已排序**,否則結果不可預期。// 數組 → List(基本類型數組會變成單元素 List)
String[] strArr = {"a","b"};
List<String> list = Arrays.asList(strArr); // 固定長度 List,不可增刪
// 基本類型陷阱
int[] prim = {1,2};
List<int[]> wrong = Arrays.asList(prim); // [[I@hash]
Integer[] boxed = {1,2};
List<Integer> right = Arrays.asList(boxed); // [1,2]
// List → 數組
List<String> list = new ArrayList<>();
list.add("x");
String[] arr = list.toArray(new String[0]); // 推薦 new String[0] 讓 JVM 推斷大小
public static String[] unique(String[] arr) {
List<String> list = new ArrayList<>();
for (String s : arr) if (!list.contains(s)) list.add(s);
return list.toArray(new String[0]);
}
// 效能測試(含裝箱開銷)
Double[] data100k = randomDoubles(100_000);
Double[] data1M = randomDoubles(1_000_000);
// 100k → ~577ms, 1M → ~5663ms(O(n²) contains 導致)
**大數據量去重建議**:改用 HashSet(O(n))或排序後相鄰比較(O(n log n))。