javaenum-map

Why EnumMap assign a Object class object for null values?


I was looking into Java EnumMap implementation and found that if I pass null value to EnumMap, EnumMap assign a Object class object in place of just null Value.

Code from EnumMap Class:

public V put(K key, V value) {
        typeCheck(key);

        int index = key.ordinal();
        Object oldValue = vals[index];
        vals[index] = maskNull(value);
        if (oldValue == null)
            size++;
        return unmaskNull(oldValue);
}

private Object maskNull(Object value) {
        return (value == null ? NULL : value);
}

private static final Object NULL = new Object() {
            public int hashCode() {
                return 0;
            }

            public String toString() {
                return "java.util.EnumMap.NULL";
            }
   };

My question is why java place a object in place of direct assigning a null value to given key. What kind of benefit java gets doing so.


Solution

  • It allows to distinguish between keys which were never added to the map and ones that were added with null value. You can see this even in the code you quoted:

    if (oldValue == null)
        size++;
    

    If null was previously put into the map with this key, oldValue will be NULL and the size will not be changed.