![]() |
VOOZH | about |
HashMap and WeakHashMap are implementations of the Map interface, but they differ significantly in how they interact with the Garbage Collector (GC). The key difference lies in the type of reference used for map keys.
HashMap stores key–value pairs using strong references for keys. As long as a key is present in a HashMap, it is not eligible for garbage collection, even if no other references to that key exist.
The entries remain in the map until explicitly removed.
This depicts that HashMap maintains a strong reference to its keys. Even after removing the external reference and invoking garbage collection, the key–value pair remains in the map.
Output:
{demo=Hi}
{demo=Hi}
Explanation: Even after removing the external reference (d = null), the object remains reachable through the HashMap, preventing garbage collection.
WeakHashMap stores keys using weak references. If a key has no strong references elsewhere, it becomes eligible for garbage collection, and the corresponding entry is automatically removed.
Garbage Collector dominates over WeakHashMap.
This code example shows how WeakHashMap uses weak references for its keys. Once the key loses its strong reference, the garbage collector removes the entry automatically from the map.
Output:
{demo = Hi}
finalize method is called
{ }
Explanation: Once the key loses its strong reference, it is garbage collected and the corresponding map entry is removed automatically.
Reference Type | Description |
|---|---|
Strong Reference | Default reference type; object is not eligible for GC |
Weak Reference | Object becomes eligible for GC when no strong references exist |
Feature | HashMap | WeakHashMap |
|---|---|---|
Reference Type | Strong | Weak |
GC Behavior | Prevents GC | Allows GC |
Entry Removal | Manual | Automatic |
Memory Leaks | Possible | Less likely |
Implements Cloneable | Yes | No |
Typical Use Case | General-purpose storage | Caches, metadata storage |