Sunday, April 9, 2017



Comparing Enum with equals and ==

Compare Enum in Java - sorting - difference between equals and compareToAs I said earlier, equals method of java.lang.Enum (see below code)  uses == operator to check if two enum are equal. This means, You can compare Enum using both == and equals method. Also equals() method is declared final inside java.lang.Enum, so risk of overriding equals method. 

Here is the code of equals from java.lang.Enum class
public final boolean equals(Object other) {
        return this==other;

By the way there are subtle difference when you compare enum with == and equals method, which stems from ==  (equality operator) being operator and equals() being method. Some of these points are already discussed in difference between equals and == in Java, but we will see them here with respect to comparing Enums in Java.

1) Using == for comparing Enum can prevent NullPointerException
This one is easy to guess, but same time provide worth of money. If you compare any Enum with null, using == operator, it will result in false, but if you use equals() method to do this check, you may get NullPointerException, unless you are using calling equals in right way as shown in how to avoid NullPointerException in Java. Look at below code, here we are comparing an unknown Shape object with Shape enum which contains CIRCLE, RECTANGLE etc.
private enum Shape{
private enum Status{
        ON, OFF;

Shape unknown = null;
Shape circle = Shape.CIRCLE;
boolean result = unknown == circle; //return false
result = unknown.equals(circle); //throws NullPointerException
I agree this can be avoided by simply comparing known to unknown i.e. circle.equals(unknown), but this is one of the most common coding error Java programmers make. By using == to compare enum, you can completely avoid it.

2) == method provides type safety during compile time
Another advantage of using == to compare enum is, compile time safety. Equality or == operator checks if both enum object are from same enum type or not at compile time itself, while equals() method will also return false but at runtime. Since it's always better to detect errors at compile time, == scores over equals in case of comparing enum. If you are using Eclipse or Netbeans, you can detect these error as soon as you type. By the way Netbeans also shows warning when you call equals() method on two incomparable types, but that is completely IDE specific.

3) == should be faster than equals method
This is more from common sense, using operator should be a touch faster than calling method, and than using operator. Though I believe modern JIT compiler might inline equals() method, when you compare two enums in Java. Which means this would not be big difference in terms of performance.But, without any smartness from compiler or JVM, I think == should always be touch faster.

Comparing Enums with compareTo method

When we say comparing enum, it's not always checking if two enums are equal or not. Sometime you need to compare them for sorting or to arrange them in a particularly order. We know that we can compare objects using Comparable and Comparator in Java and enum is no different, though it provides additional convenience. Java.lang.Enum implements Comparable interface and it's compareTo() method compares only same type of enum. Also natural order of enum is the order in which they are declared in code. As shown on 10 examples of Enum in Java, same order is also maintained by ordinal() method of enum, which is used by EnumSet and EnumMap.
public final int compareTo(E o) {
        Enum other = (Enum)o;
        Enum self = this;
        if (self.getClass() != other.getClass() && // optimization
            self.getDeclaringClass() != other.getDeclaringClass())
            throw new ClassCastException();
        return self.ordinal - other.ordinal;

If you look last line, it's using ordinal to compare two enum in Java.

That's all on How to compare two enum in Java and difference between == and equals to compare two enums. Though using equals() to compare object is considered Java best practice, comparing Enum using == is better than using equals. Don't forget ordinal() and compareTo() methods, which is also key to get natural order of Enum during comparison.

Recommended Reading on Java Enum

If you want to learn more about Enum, I suggest reading following Java books. Books are best resource to learn deep about any topic and I personally follow them as well. Enumeration types chapter from Thinking in Java is particularly useful. 

Thinking in Java (4th Edition) By Bruce Eckel

Java 5.0 Tiger: A Developers notebook
Effective Java by Joshua Bloch


Further Reading
Java Fundamentals, Part 1 and 2
Core Java For the Impatient - Covers Java SE 8
Java Fundamentals: The Java Language



Hi Javin ,

Gr8 article, it will help a developers to understand the concepts more,..few things that I want to like add is...

*** Can == be used on enum?


JLS 8.9 Enums





What are the differences between == and equals?


== never throws NullPointerException

enum Color { BLACK, WHITE };

Color nothing = null;
if (nothing == Color.BLACK); // runs fine
if (nothing.equals(Color.BLACK)); // throws NullPointerException
== is subject to type compatibility check at compile time

enum Color { BLACK, WHITE };
enum Chiral { LEFT, RIGHT };

if (Color.BLACK.equals(Chiral.LEFT)); // compiles fine
Should == be used when applicable?


Item 1: Consider static factory methods instead of constructors



It works.
It's faster.
It's safer at run-time.
It's safer at compile-time.

Javin @ ClassLoader in Java said...

As always Great Comment Saral, and thanks for adding value and sharing that JLS reference.

Anonymous said...

Hello there, == breaks type abstraction where equals() does not.

Post a Comment

Pepperjam Verification