A WeakHashMap holds its keys through weak references but its values through ordinary strong ones, so an entry is only ever cleared by the key becoming unreachable. While a strong reference to the key exists, the map behaves exactly like a normal one.
Map<String, String> weak = new WeakHashMap<>();
String key = new String("session-42");
weak.put(key, "active");
System.out.println("Contains key while strongly referenced: " + weak.containsKey(key));
System.out.println("Value retrieved: " + weak.get(key));
System.out.println("Size: " + weak.size());
Contains key while strongly referenced: true
Value retrieved: active
Size: 1
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-09-27