开发者

The best way to compare enums [duplicate]

This question already has answers here: Comparing Java enum members: == or equals()? 开发者_StackOverflow社区 (15 answers) Closed 5 years ago.

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
}

or

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.

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:
        //...
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜