这是今天写代码时遇到的需要比较枚举的问题。在使用 “equals” 还是 “==” 之间犹豫了好久
首先给出答案。都可以,但是用 == 更好
我们发现,equals的底层点击去看就会发现其实就是 ==
而枚举是单例模式的,所以可以直接用 == 直接比较值。
那么,什么时候 == 和 equals 不一样?
在stackoverflow上我们找到了答案
As a reminder, it needs to be said that generally, == is NOT a viable alternative to equals. When it is, however (such as with enum), there are two important differences to consider.
翻译过来是,通常来说 == 不是一个 equals的一个备选方案,无论如何有2个重要的不同处需要考虑。
- == 不会抛出 NullPointerException
enum Color {
BLACK, WHITE
};
Color nothing = null;
if (nothing == Color.BLACK); // runs fine
if (nothing.equals(Color.BLACK)); // throws NullPointerException
- == 在编译期检测类型兼容性
enum Color {
BLACK, WHITE
};
enum Chiral {
LEFT, RIGHT
};
if (Color.BLACK.equals(Chiral.LEFT)); // compiles fine
if (Color.BLACK == Chiral.LEFT); // DOESN'T COMPILE!!! Incompatible types!
在一些大型互联网公司,已经加了强制的代码扫描规则,枚举比较需要使用 == 比较,因为 == 具有性能更优和避免空指针的好处。而且能在编译中检测出一些枚举类型不一致的手误,避免由此引发的线上case.
参考
https://stackoverflow.com/questions/1750435/comparing-java-enum-members-or-equals
版权声明:本文为guanghuichenshao原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。