javaenum-map

Why does EnumMap implementation check for the key's superclass?


private boolean isValidKey(Object key) {
    if (key == null)
        return false;

    // Cheaper than instanceof Enum followed by getDeclaringClass
    Class<?> keyClass = key.getClass();
    return keyClass == keyType || keyClass.getSuperclass() == keyType;
}

As seen in the above method's last line, why does EnumMap implementation check for the key's superclass? If nothing can derive from an enum why is this check needed?


Solution

  • You can declare enum constants with bodies to customize their behavior

    enum Bar {
        NORMAL, CUSTOM {
            @Override
            public String toString() {
                return "different";
            }
        };
    }
    

    These constants are implemented as subclasses of the enum type.

    The optional class body of an enum constant implicitly defines an anonymous class declaration (§15.9.5) that extends the immediately enclosing enum type.

    For the EnumMap map to work with all the enum constants, it therefore needs to check for this possibility by checking that the key's superclass is the enum type used to initialize the EnumMap (the keyType).