ArrayList<String> list = new ArrayList<>();
String[] strings = (String[]) list.toArray(); // 執行時拋出 ClassCastException
錯誤原因:toArray() 無參版本返回 Object[],無法向下轉型為 String[]。JVM 執行時檢查陣列實際類型是 Object[],非 String[]。
String[] strings = new String[list.size()];
for (int i = 0; i < list.size(); i++) {
strings[i] = list.get(i);
}
String[] strings = list.toArray(new String[0]);
// 或預估大小優化:
String[] strings = list.toArray(new String[list.size()]);
原理:JDK 內部使用反射 Array.newInstance(componentType, size) 建立正確類型陣列。
toArray(IntFunction)String[] strings = list.toArray(String[]::new);
// ArrayList 內部實現
public <T> T[] toArray(T[] a) {
if (a.length < size)
a = (T[]) java.lang.reflect.Array.newInstance(
a.getClass().getComponentType(), size);
System.arraycopy(elementData, 0, a, 0, size);
if (a.length > size) a[size] = null;
return a;
}
Java 泛型陣列無法直接 new T[size] (類型擦除),必須透過反射根據傳入陣列的組件類型動態建立。
String[] arr = {"a", "b", "c"};
List<String> list = Arrays.asList(arr); // 返回固定大小 List
// 若需可修改 List:
List<String> modifiableList = new ArrayList<>(Arrays.asList(arr));
| 方法 | 適用場景 | 效能 | 備註 |
|---|---|---|---|
toArray(new T[0]) | 一般用途 | 良好 | JDK 內部優化,推薦 |
toArray(new T[size]) | 大集合、追求極致 | 最佳 | 避免擴容複製 |
toArray(T[]::new) | Java 11+ | 良好 | 語法簡潔,內部同樣優化 |
| 手動 for 迴圈 | 特殊邏輯處理 | 較慢 | 避免除非必要 |