Collections: WeakHashMap wraps keys, not values, in weak references

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.

Code
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());
Output
Contains key while strongly referenced: true
Value retrieved: active
Size: 1
Advertisement
More in JAVA

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

© Java Coding Hub · About · Contact · Privacy · Terms