Search code examples
javaenum-map

EnumMap.containsValue(null) returns true JDK 7


I found a strange behavior. I m using JDK 1.7. When I print map.containsValue(null)

it returns true though I don't have any null value in my MAP.

import java.util.EnumMap;
import java.util.Map;

public class EnumMapTest {
    enum EnumType {
        ZERO, ONE, TWO
    }

    public static void main(String[] args) {
        Map<EnumType, Integer> map = new EnumMap<EnumType, Integer>(EnumType.class);
        map.put(EnumType.ZERO, 0);
        System.out.println(map.containsValue(null));
    }
}

Solution

  • This is because it inspects all the values for all the possible keys. In your case

    map.get(ONE) is null
    map.get(TWO) is null
    

    In Java 8 it doesn't do this. Instead distinguishes between null as in not set and NULL which is a value set to null.