Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The best way to compare enums [duplicate]

Tags:

java

enums

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
}
like image 369
Colin Avatar asked Jul 29 '11 15:07

Colin


1 Answers

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:
        //...
}
like image 121
Mark Peters Avatar answered Sep 19 '22 01:09

Mark Peters