CKTIS / Java
WeakHashMap — a map with weak keys
WeakHashMap holds keys through weak references: the map alone does not protect them from garbage collection. Learn put, get, containsKey, containsValue, and size, including the distinction between a missing entry and a null value.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
WeakHashMap<K, V> map = new WeakHashMap<>();
V previous = map.put(key, value);
V retrieved = map.get(key);
boolean hasKey = map.containsKey(key);
boolean hasValue = map.containsValue(value);
int count = map.size();java.util.WeakHashMap<K, V> is a hash-based map with weak keys. A weak reference does not prevent the garbage collector (GC) from reclaiming an object. The map can therefore lose an entry after its key is collected; removal timing is nondeterministic.
WeakHashMap.put(key, value) adds or replaces a value and returns the previous value or null (no entry or a previous null value). WeakHashMap.get(key) returns the value or null. WeakHashMap.containsKey(key) checks for an entry, distinguishing absence from a null mapping; WeakHashMap.containsValue(value) checks for a value. WeakHashMap.size() returns a snapshot count that can decrease without explicit mutations.
The null key and null values are allowed. Lookup respects equals and hashCode, not just object identity. Values are held strongly: their direct or indirect references to keys can prevent collection. The map is not synchronized; synchronization does not prevent GC-driven removal.
The example keeps key reachable until Reference.reachabilityFence(key) so its output does not depend on GC. It demonstrates replacing a value and the distinction between get(key) returning null and the key being present.
Examples
import java.lang.ref.Reference;
import java.util.WeakHashMap;
public class Main {
public static void main(String[] args) {
Object key = new Object();
WeakHashMap<Object, String> map = new WeakHashMap<>();
try {
System.out.println(map.put(key, "draft"));
System.out.println(map.put(key, "ready"));
System.out.println(map.get(key));
System.out.println(map.containsKey(key));
System.out.println(map.containsValue("ready"));
System.out.println(map.size());
map.put(key, null);
System.out.println(map.get(key));
System.out.println(map.containsKey(key));
} finally {
Reference.reachabilityFence(key);
}
}
}Result
null draft ready true true 1 null true
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.