比较枚举的最佳方式 [英] The best way to compare enums

查看:120
本文介绍了比较枚举的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

Color c1 = Brown, c2 = Red

与常数值进行比较的最佳方法是:

What is best way to compare to a constant value:

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

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


推荐答案

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

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.

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

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

个人我很少发现自己使用如果枚举的语句。我喜欢开关块。

Personally I very seldom find myself using if statements for enums at all. I favour switch blocks.

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

这篇关于比较枚举的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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