Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't java.lang.Enum::valueOf check for the null name first?

Tags:

java

enums

I have checked the source code for java.lang.Enum and the method T valueOf(Class<T> enumType, String name) beginning on line 232 (the implementation in both java-8 and java-11 seems equal; here is the source for Java 8).

public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name) {
    T result = enumType.enumConstantDirectory().get(name);
    if (result != null)
        return result;
    if (name == null)
        throw new NullPointerException("Name is null");
    throw new IllegalArgumentException(
        "No enum constant " + enumType.getCanonicalName() + "." + name);
}

What is the reason the null check for name happens after finding the enumeration by name in the Map get using enumConstantDirectory()? As far as I know, one cannot define a null enum; therefore the following call makes no sense:

MyEnum myEnum = Enum.valueOf(MyEnum.class, null);     // The NPE should be thrown

Although the HashMap implementation allows null as a key, I would expect the implementation would check for null before iterating the Map. What is the reason for this implementation and is there a case where searching for the null key before comparing name == null makes sense?

like image 1000
Nikolas Charalambidis Avatar asked Jun 24 '20 10:06

Nikolas Charalambidis


People also ask

Can enum have NULL value in Java?

An ENUM can also contain NULL and empty values. If the ENUM column is declared to permit NULL values, NULL becomes a valid value, as well as the default value (see below).

Can we add NULL value in enum?

If you want to represent null with an enum, then you'll have to explicit this by using a null object pattern manually with a NONE value and a custom implementation for prettyPrint() based on NONE value.

How do you check if an enum is valid?

The Enum . IsDefined method should be used to determine whether a valid enumeration value has been passed to any method that accepts an enumeration value as a parameter. In particular, this Enum. IsDefined should always be used whenever the method is visible to external objects.


1 Answers

99.999+% of calls to that method will be valid enum names. Passing a null name is always a blunder and is not the case that you want to optimize for. So moving the null check three lines down means that the check will be skipped in the common case that the enum name is valid. It doesn't change the result; it's just a tiny optimization.

like image 94
Boann Avatar answered Oct 28 '22 15:10

Boann