Clean • Professional
WeakHashMap is a special Map implementation in Java where the keys are stored as weak references. This means if a key is no longer strongly referenced elsewhere, it can be garbage collected, and its entry is automatically removed from the map.
It is part of the java.util package.
import java.util.WeakHashMap;
Collections.synchronizedMap() for thread safety.Iterable
└── Collection
└── Map
└── WeakHashMap
Internal Diagram (Example)
Key (WeakRef) → Value
A (weak) → 10
B (weak) → 20
C (weak) → 30
A is no longer referenced elsewhere, GC removes it → entry gone from map.Default Constructor
Creates an empty WeakHashMap with default capacity (16) and load factor (0.75).
WeakHashMap<K, V> map = new WeakHashMap<>();
With Initial Capacity
Creates a WeakHashMap with the given starting capacity to reduce early resizing.
WeakHashMap<K, V> map = new WeakHashMap<>(32);
With Initial Capacity & Load Factor
Creates a map with full control over initial capacity and load factor for performance tuning.
WeakHashMap<K, V> map = new WeakHashMap<>(32, 0.75f);
From Another Map
Creates a WeakHashMap by copying all entries from an existing map, converting the keys to weak references.
Map<K, V> existingMap = new HashMap<>();
WeakHashMap<K, V> map2 = new WeakHashMap<>(existingMap);

| Method | Description |
|---|---|
put(K key, V value) | Adds or updates a key-value pair (key stored as a weak reference). |
get(Object key) | Returns the value for the given key, or null if not found or garbage-collected. |
remove(Object key) | Removes the mapping for the given key. |
containsKey(Object key) | Checks if the map contains the given key (if not garbage-collected). |
containsValue(Object value) | Checks if the map contains the given value. |
size() | Returns the number of active entries (expired weak keys are automatically removed). |
isEmpty() | Checks if the map has no valid entries. |
keySet() / values() / entrySet() | Returns views of keys, values, or entries. |
clear() | Removes all entries from the map. |
putAll(Map m) | Copies all entries from another map. |
Note: When a key is garbage collected, its entry is automatically removed.
Example
import java.util.WeakHashMap;
public class Main {
public static void main(String[] args) {
WeakHashMap<String, String> map = new WeakHashMap<>();
String key1 = new String("A");
String key2 = new String("B");
map.put(key1, "Apple");
map.put(key2, "Banana");
System.out.println("Before GC: " + map);
key1 = null; // key1 no longer strongly referenced
System.gc(); // suggest garbage collection
try { Thread.sleep(1000); } catch (InterruptedException e) {}
System.out.println("After GC: " + map);
}
}
Possible Output:
Before GC: {A=Apple, B=Banana}
After GC: {B=Banana}
| Operation | Average |
|---|---|
| put() | O(1) |
| get() | O(1) |
| remove() | O(1) |
| containsKey() | O(1) |
| iteration | O(n) |
| Feature | HashMap | WeakHashMap |
|---|---|---|
| Key Reference | Strong references | Weak references |
| Garbage Collection | Keys are never garbage collected automatically | Keys are automatically removed when no strong reference exists |
| Null Keys | Allows 1 null key | Allows 1 null key |
| Null Values | Allows multiple null values | Allows multiple null values |
| Thread-Safety | Not thread-safe | Not thread-safe (wrap with Collections.synchronizedMap() if needed) |
| Iteration | Fail-fast | Fail-fast |
| Use Case | General-purpose map | Memory-sensitive caches, temporary mappings, canonicalizing objects |
| Memory Management | Keys remain until explicitly removed | Helps avoid memory leaks for keys no longer in use |
| Performance | Fast, standard hash-based operations | Similar to HashMap, but additional overhead for weak references and reference queue handling |
ConcurrentModificationExceptionCollections.synchronizedMap() if needed