A detailed introduction to WeakHashMap in the Java collections series.
WeakHashMap is a special implementation class of Map in Java collections, which inherits from the AbstractMap class and implements the Map interface. The key feature of WeakHashMap is that its keys are weak references, meaning that if a key is not referenced by any other object, it will be automatically removed along with its corresponding value when the garbage collector runs.
The weak reference feature of WeakHashMap makes it very useful in certain specific scenarios. For instance, when we need to cache a large number of objects, using HashMap as the cache may lead to memory overflow issues. However, if WeakHashMap is used as the cache, when the cached key is not referenced by other objects, the garbage collector will automatically remove this key and its corresponding value, thereby freeing up memory space.
Aside from the weak reference feature, WeakHashMap is essentially the same as HashMap in other aspects. It allows storing null values and null keys, and its operational complexity is also the same as HashMap. However, due to the weak reference feature of WeakHashMap, its performance may be slightly lower than HashMap.
Below is an example of using WeakHashMap:
import java.util.Map;
import java.util.WeakHashMap;
public class WeakHashMapExample {
public static void main(String[] args) {
Map<Key, Value> map = new WeakHashMap<>();
Key key1 = new Key(1);
Value value1 = new Value("value1");
Key key2 = new Key(2);
Value value2 = new Value("value2");
map.put(key1, value1);
map.put(key2, value2);
System.out.println(map); // {Key@1=Value[value1], Key@2=Value[value2]}
key1 = null;
System.gc();
System.out.println(map); // {Key@2=Value[value2]}
}
}
class Key {
private int id;
public Key(int id) {
this.id = id;
}
@Override
public String toString() {
return "Key@" + id;
}
}
class Value {
private String value;
public Value(String value) {
this.value = value;
}
@Override
public String toString() {
return "Value[" + value + "]";
}
}
In the example above, we created a WeakHashMap object and stored two key-value pairs in it. We then set the first key to null and manually ran the garbage collector. Finally, when we printed the contents of the map, we could see that the first key and its corresponding value had been automatically removed.
It is important to note that both the key and value in WeakHashMap are weak references, so care should be taken when handling object references to avoid unexpected situations when using WeakHashMap.