Collections Framework 設計之初即以「完全互操作性」為核心目標,確保新集合介面與舊有 Vector、Hashtable、陣列、Enumeration 雙向無縫轉換。本文詳細說明相容性轉換技巧與 API 設計黃金法則。
Foo[] result = oldMethod(arg);
newMethod(Arrays.asList(result)); // 陣列視圖為 List
JDK 1.2 已改造實現對應介面,零成本轉換:
Vector<String> v = oldMethod(arg);
newMethod(v); // Vector 即 List
Hashtable<String, String> h = oldMethod(arg);
newMethod(h); // Hashtable 即 Map
Enumeration<String> e = oldMethod(arg);
List<String> list = new ArrayList<>();
while (e.hasMoreElements())
list.add(e.nextElement());
newMethod(list);
Collection<String> c = newMethod();
oldMethod(c.toArray()); // Object[]
// 指定型別陣列
oldMethod(c.toArray(new String[0])); // String[]
Collection<String> c = newMethod();
oldMethod(new Vector<>(c)); // 標準建構子
Map<String, String> m = newMethod();
oldMethod(new Hashtable<>(m));
Collection<String> c = newMethod();
oldMethod(Collections.enumeration(c)); // 靜態工廠方法
ArrayList、HashMap 等)Collection 別用 List/Set;需有序/唯一性保證時才用 List/SetList,因依賴有序性SortedMap 時宣告 SortedMap 而非 Map,賦予呼叫端更豐富功能Collection 但返回 ImageList 實現 List)new LegacyCollection(standardCollection)遵循這些規範,你的 API 將與整個 Java 生態系統無縫協作,充分發揮 Collections Framework 的網絡效應。