11

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 and 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?

4
  • 6
    Maybe so that the most frequent path happens first. Commented Jun 24, 2020 at 10:30
  • 1
    I think this is a good question. Without knowing it, my assumption is that this part was implemented afterwards to make the API 'better'. From my oppinion there is no rease why this check is doing afterwards. Commented Jun 24, 2020 at 10:31
  • 5
    It's an interesting question, though I don't think fits SO because we are not the authors, and we can only guess, not give an authoritative answer. My guess: They wanted to give precedence to the exception that is thrown if the class is not a real Enum class. That is, if both arguments are incorrect, you want to throw an exception for the first argument first, and only if it's legal, throw an exception for the second argument. Commented Jun 24, 2020 at 10:58
  • Maybe to make faster the happy case (generally that will be used most), especially when the previous operation don't make any problem with null value Commented Jun 24, 2020 at 11:59

1 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.