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?