6

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
}
Mark Peters
  • 80,126
  • 17
  • 159
  • 190
Colin
  • 251
  • 2
  • 4
  • 8

1 Answers1

13

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:
        //...
}
Mark Peters
  • 80,126
  • 17
  • 159
  • 190