Summary
The best way to compare enums in Java is == operator, like in an example below:
1 2 3 4 |
Color white = Color.WHITE; System.out.println(white == Color.WHITE); |
Comparison of == and equals methods
There are two ways to compare enums in java: == operator and equals() method.
First of all, I would like to show you an implementation of method equals() of java.lang.Enum:
1 2 3 4 5 |
public final boolean equals(Object other) { return this==other; } |
As you can see, the equals() method of java.lang.Enum uses the == operator. This means you can use both to compare Enums. So, when we run the code below:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public enum Color { WHITE, YELLOW, ORANGE, RED, PINK, PURPLE, BLUE, GREEN, BROWN, BLACK } if (Color.WHITE == Color.WHITE) { System.out.println(Color.WHITE + " equals " + Color.WHITE); } if (Color.BLACK.equals(Color.BLACK)) { System.out.println(Color.BLACK + " equals " + Color.BLACK); } |
The result is:
1 2 3 4 |
WHITE equals WHITE BLACK equals BLACK |
But due to == being an operator and equals() being method, there are subtle differences.
Using equals() can cause NullPointerException
Let’s declare two variables of type Color:
1 2 3 4 |
Color unknown = null; Color blue = Color.BLUE; |
and compare them using == operator:
1 2 3 |
System.out.println(unknown == blue); |
Everything is alright because if we compare any Enum with null like this, it will print false.
But if we try to compare those variables using equals() method:
1 2 3 |
System.out.println(unknown.equals(blue)); |
we will get NullPointerException.
1 2 3 |
Exception in thread "main" java.lang.NullPointerException |
== operator provides compile-time checking
Compile time safety is another advantage of using == operator. This operator checks if both objects are the same enum type at compile time. Equals() method does not do that because of contract (Object.equals(Object)), so we can expect a RuntimeException.
We should use an == operator, since detecting errors at compile time is always better.