java - Why doesn't java.lang.Enum::valueOf check for the null name first?
问题描述
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?
解决方案
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.
推荐阅读
- php - 如何检查特定数据是否存在于数据数组中
- swift - SwiftUI + Combine,一起使用 Models 和 ViewModels
- django - 无法访问 url 中的 Django 查询字符串参数
- python - 为什么我会收到 MemoryError?
- c++ - 为什么数字在 C++ 中超出了长期范围?
- android - Android R:API 30:系统栏可见性更改回调
- java - 如何使用 ClientBuilder 为 Rest Post Api MultiPart 编写集成测试
- java - 无法通过代理从 Firebase Java 应用程序发送通知到移动应用程序
- android - ImageView 的原生圆形波纹效果
- javascript - 无法使用 indexof 匹配值