Khác mục đích, nhưng dưới mui xe là cùng một thứ.
| HashSet<E> | HashMap<K,V> | |
|---|---|---|
| Implements | Set | Map |
| Lưu trữ | Phần tử duy nhất | Cặp key → value |
| Method | add, contains, remove | put, get, remove |
Sự thật: HashSet thực ra là wrapper của HashMap — value là dummy object dùng chung:
java
// HashSet rút gọn
public boolean add(E e) { return map.put(e, PRESENT) == null; }
public boolean contains(Object o) { return map.containsKey(o); }Khi dùng:
- "Có phần tử này không?" → HashSet.
- "Map key → giá trị" → HashMap.
java
Set<String> visited = new HashSet<>();
visited.add("java");
Map<String, Integer> count = new HashMap<>();
for (String w : words) count.merge(w, 1, Integer::sum);Yêu cầu chung: element/key phải override hashCode() + equals() đúng. record (Java 16+) tự sinh đúng cả hai → default cho key.