Best way to compare listings

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

 Color c1 = Brown, c2 = Red 

What is best compared to a constant value:

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

or

 if (c1.equals(Color.Brown)) { //is brown } 
+6
source share
1 answer

Use == . There cannot be several instances of the same enum constant (in the context of the class loader, but let it ignore this point), so it is always safe.

However, using equals() also safe and will also perform referential equality. It is pretty much a style choice.

Personally, I rarely see if for enumerations in general. I prefer switch blocks.

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

Source: https://habr.com/ru/post/893878/


All Articles