比较 Java 枚举成员:== 还是 equals()? [英] Comparing Java enum members: == or equals()?

查看:23
本文介绍了比较 Java 枚举成员:== 还是 equals()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 Java 枚举被编译为具有私有构造函数和一堆公共静态成员的类.在比较给定枚举的两个成员时,我总是使用 .equals(),例如

I know that Java enums are compiled to classes with private constructors and a bunch of public static members. When comparing two members of a given enum, I've always used .equals(), e.g.

public useEnums(SomeEnum a)
{
    if(a.equals(SomeEnum.SOME_ENUM_VALUE))
    {
        ...
    }
    ...
}

然而,我刚刚遇到了一些使用等于运算符 == 而不是 .equals() 的代码:

However, I just came across some code that uses the equals operator == instead of .equals():

public useEnums2(SomeEnum a)
{
    if(a == SomeEnum.SOME_ENUM_VALUE)
    {
        ...
    }
    ...
}

我应该使用哪个运算符?

Which operator is the one I should be using?

推荐答案

两者在技术上都是正确的.如果您查看 .equals() 的源代码,它只是遵循 ==.

Both are technically correct. If you look at the source code for .equals(), it simply defers to ==.

我使用 ==,但是,因为它是空安全的.

I use ==, however, as that will be null safe.

这篇关于比较 Java 枚举成员:== 还是 equals()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆