tags:

views:

131

answers:

1

Is there a convenience method available in the java standard libraries to check whether all possible keys in an EnumMap are mapped to a value?

I can write my own method like:

public static <T extends Enum<T>> boolean areAllValuesMapped(EnumMap<T, ?> map, Class<T> enumClass)
{
    return map.keySet().equals(EnumSet.allOf(enumClass));
}

But then I'm repeating the Class parameter (already given in the EnumMap constructor) as well as creating throwaway KeySet and EnumSet objects. EnumMap should have enough information to do this efficiently as an internal operation.

+3  A: 

There is no built-in way to do this that I can find in EnumMap (and I checked the source code to be sure). However, here is a slightly quicker method:

public static <T extends Enum<T>> boolean areAllValuesMapped(EnumMap<T,?> map, Class<T> enumClass) {
    return map.size() == enumClass.getEnumConstants().length;
}

I should note that EnumMap.keySet() does not return an EnumSet; if it did, the equals() call that you use would be a simple matter of comparing longs. As it is, it has to use an iterator and check each enum constant sequentially.

Michael Myers