Null keys

Report a typo

WeakHashMap has a field to mask a null key: private static final Object NULL_KEY = new Object();
When you add a null key, the field itself becomes a key. Once added, such a key will always have a strong reference to it.
Based on this statement, find the map size at the end of this snippet.

public class WeakHashMapDemo {
    public static void main(String[] args) throws InterruptedException {
        Person joshua = new Person("Joshua Bloch", 1961);
        Person bruce = new Person("Bruce Eckel", 1957);
        Person person = joshua;

        Map<Person, String> map = new WeakHashMap();
        map.put(joshua, "Effective Java");
        map.put(bruce, "Thinking in Java"); 
        map.put(null, "No Title");
        
        joshua = null;
        System.gc();
        Thread.sleep(250);

        System.out.println(map.size());
    }
}
Enter a number
___

Create a free account to access the full topic