The best way to compare enums [duplicate]
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:
//...
}
精彩评论