3

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.

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

To expand on this a little - it's a consequence of the fact that since the keys are Enums, the value store is a pre-allocated array of known size - all possible keys are directly mapped to values, there are no buckets and nothing can collide. A tag value is needed to so the empty value elements can be distinguished from the ones where an explicit null was inserted.
And to expand on that, null is used for empty elements and NULL for null ones (rather than vice versa) because this way, newly allocated array immediately represents an empty map.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.