Junior — Middle
Can you explain how the WeakHashMap class works in Java and how it differs from a regular HashMap?
sobes.tech AI
Answer from AI
The WeakHashMap class in Java is an implementation of the Map interface where keys are stored using weak references (WeakReference). This means that if there are no strong references to a key in the program, it can be garbage collected, and the corresponding key-value pair will be automatically removed from the map.
Differences from a regular HashMap:
- In
HashMap, keys and values are stored through strong references, so objects used as keys are not garbage collected as long as they are in the map. - In
WeakHashMap, keys are weak references, which allows the map to automatically clean up entries whose keys are no longer used in the program.
Example usage:
import java.util.WeakHashMap;
public class WeakHashMapExample {
public static void main(String[] args) {
WeakHashMap<Object, String> map = new WeakHashMap<>();
Object key = new Object();
map.put(key, "value");
System.out.println("Before nulling key: " + map);
key = null; // Remove strong reference to the key
System.gc(); // Request garbage collection
// After some time, the entry may be removed
System.out.println("After GC: " + map);
}
}
Thus, WeakHashMap is useful for caching, where entries should be automatically removed when there are no external references to the keys.