问题描述
枚举名称是否存在于 Java 中?
Are enum names interned in Java?
即是否保证 enum1.name() == enum2.name()
在同名的情况下?将 enum.name()
与保证被实习的字符串进行比较是否安全.
I.e. is it guaranteed that enum1.name() == enum2.name()
in case of the same name? And is it safe to compare enum.name()
to a String that is guaranteed to be interned.
推荐答案
虽然没有明确保证这一点,但最终结果必然是对于 enum
常量的比较总是成功的同名:
Although there is no explicit guarantee of this, the end result is bound to be such that the comparison always succeeds for enum
constants with identical names:
enum A {enum1};
enum B {enum1};
System.out.println(A.enum1.name() == B.enum1.name()); // Prints "true"
这样做的原因是 Java 编译器以这样一种方式构造 Enum
的子类,它们最终会调用 Enum
唯一受保护的构造函数,并将其名称传递给它enum
值:
The reason for this is that Java compiler constructs subclasses of Enum
in such a way that they end up calling Enum
's sole protected constructor, passing it the name of enum
value:
protected Enum(String name, int ordinal);
名称以字符串文字的形式嵌入到生成的代码中.根据 String
文档,
The name is embedded into the generated code in the form of a string literal. According to String
documentation,
所有文字字符串和字符串值常量表达式都被插入.
这相当于当 enum
常量的名称相同时表达式成功的隐式保证.但是,我不会依赖这种行为,而是使用 equals(...)
代替,因为任何阅读我的代码的人都会挠头,认为我犯了一个错误.
This amounts to an implicit guarantee of your expression succeeding when names of enum
constants are identical. However, I would not rely on this behavior, and use equals(...)
instead, because anyone reading my code would be scratching his head, thinking that I made a mistake.
这篇关于枚举名称是否存在于 Java 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!