List 和 Set 都是 Collection 接口的子接口,但語義、特性、實現類及適用場景截然不同。
| 特性 | List | Set |
|---|---|---|
| 有序性 | 有序(按插入順序維護) | 無序(HashSet)或排序(TreeSet) |
| 重複元素 | 允許重複 | 不允許重複(依賴 equals()) |
| 索引訪問 | 支持 get(index) 隨機訪問 | 不支持索引訪問 |
| Null 元素 | 允許多個 null | 最多允許一個 null (HashSet/LinkedHashSet) |
| 主要實現類 | ArrayList, LinkedList, Vector | HashSet, LinkedHashSet, TreeSet |
Collections.synchronizedList 或 CopyOnWriteArrayList 替代。hashCode() 和 equals()。ArrayList:連續內存數組LinkedList:離散節點鏈表HashSet:哈希表(數組+鏈表/紅黑樹)TreeSet:紅黑樹List list = new ArrayList<>(); 便於後期替換實現。ArrayListLinkedListHashSetLinkedHashSetTreeSet