Middle
What is the difference between HashMap and WeakHashMap in Java?
sobes.tech AI
Answer from AI
The main difference is how they handle their keys. HashMap uses strong references to keys, while WeakHashMap uses weak references.
HashMap:
- Uses strong references. Once an object is used as a key in
HashMap, the garbage collector GC cannot delete this object as long as theHashMapexists and holds a reference to this key. - Not suitable for caching objects whose lifecycle should be determined by external factors, as keys will be "held" preventing their collection.
- Used when it is necessary to guarantee the constant presence of all added keys until the map is cleared or elements are manually removed.
WeakHashMap:
- Uses weak references to keys. If there are no strong references to the key object outside of
WeakHashMap, the garbage collector can collect it, even if it still exists inWeakHashMap. - When a key is collected by the garbage collector, the corresponding entry (key-value pair) is automatically removed from
WeakHashMap. This occurs during map operations (e.g.,get,put,remove) or during garbage collection. - Ideal for implementing caches where objects need to be stored but their removal by the garbage collector should not be hindered if they are not used elsewhere (weak reference does not hold the object).
- Iteration over
WeakHashMapcan be incomplete or contain references to already collected keys (although the corresponding entries will be removed later).
Comparison table:
| Attribute | HashMap | WeakHashMap |
|---|---|---|
| Key reference type | Strong | Weak |
| Key garbage collection | Impossible as long as the key is in the map and the map is accessible | Possible if there are no strong references outside |
| Entry removal | Only manually or during map clearing | Manually or automatically during key collection |
| Applicability | General purpose, when keys should be preserved | Caching, when keys can be garbage collected |
| Performance | Usually stable | May vary due to interaction with GC |