LinkedHashSet 是 HashSet 的有序版本,內部通過雙向鏈表維護元素插入順序。它結合了 HashSet 的高性能查找與鏈表的順序特性,是需要保持插入順序場景的理想選擇。
public static void test(Set<Integer> set) {
System.out.println(set.getClass().getName());
// 添加 100-110
for (int i = 100; i <= 110; i++) set.add(i);
showSet(set); // [100, 101, 102, ..., 110]
// 刪除 101
set.remove(101);
showSet(set); // [100, 102, 103, ..., 110]
// 新增元素追加到末尾
set.add(98);
set.add(101);
set.add(118);
showSet(set); // [100, 102, ..., 110, 98, 101, 118]
}
| 場景 | 推薦集合 | 理由 |
|---|---|---|
| 需要去重且保持輸入順序 | LinkedHashSet | O(1) 查找 + 順序保證 |
| 需要排序 | TreeSet | 自動排序功能 |
| 純去重、無序需求 | HashSet | 最高性能 |
| 頻繁按索引訪問 | ArrayList | 隨機訪問優勢 |
雖然 LinkedHashSet 比 HashSet 多維護鏈表開銷,但查找性能仍接近 O(1),遠優於 List 的 O(n) 線性查找。在需要頻繁去重檢查且保持順序的場景下是最佳平衡選擇。
