撒拉嘿哟木头
2009-11-17 17:26
采纳率: 40%
浏览 663
已采纳

比较 Java enum 成员: 还是等于() ?

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))
    {
        ...
    }
    ...
}

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?

转载于:https://stackoverflow.com/questions/1750435/comparing-java-enum-members-or-equals

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

15条回答 默认 最新

  • 乱世@小熊 2009-11-17 17:29
    已采纳

    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.

    评论
    解决 无用
    打赏 举报
  • 查看更多回答(14条)

相关推荐 更多相似问题