Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

enum-map

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?

like image 917
hawk Avatar asked Feb 28 '26 23:02

hawk


1 Answers

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).

like image 153
Sotirios Delimanolis Avatar answered Mar 02 '26 12:03

Sotirios Delimanolis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!