java 比较枚举的最佳方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6875677/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 17:41:56  来源:igfitidea点击:

The best way to compare enums

javaenums

提问by Colin

I have an enum, for example enum Color { Red, Brown }. I also have some variables of that type:

例如,我有一个枚举enum Color { Red, Brown }。我也有一些这种类型的变量:

Color c1 = Brown, c2 = Red

What is best way to compare to a constant value:

与常量值进行比较的最佳方法是什么:

if (c1 == Color.Brown) { 
    //is brown
}

or

或者

if (c1.equals(Color.Brown)) {
    //is brown
}

回答by Mark Peters

Use ==. There cannot be multiple instances of the same enum constant (within the context of a classloader, but let's ignore that point) so it's always safe.

使用==. 同一个枚举常量不能有多个实例(在类加载器的上下文中,但让我们忽略这一点)所以它总是安全的。

That said, using equals()is safe too, and will perform reference equality as well. It's pretty much a style choice.

也就是说, usingequals()也是安全的,并且也会执行引用相等。这几乎是一种风格选择。

Personally I very seldom find myself using ifstatements for enums at all. I favour switchblocks.

就我个人而言,我很少发现自己使用if枚举语句。我喜欢switch块。

switch (c1) {
    case Brown:
        //is brown
        break;
    case Red:
        //...
}