Comparing Enumerations in Java

Feb 24, 2018 09:23 · 257 words · 2 minutes read Java

When comparing enumerated values in Java, does == work or do we need to do .equals(), and which should be preferred if both work? The answer to the first question is, == and .equals() both yield the same answer. In fact looking at the source code to Enum.java in the standard library:

public final boolean equals(Object other) {
    return this==other;
}

We see that .equals() is internally using == anyways. The second question is a bit more nuanced, should == or .equals() be preferred. There’s an excellent SO answer for this incorporating all of the major arguments. The main argument for using == is null safety, so personally I would recommend using == when comparing Enums.

This can get a little more confusing on the surface if we start adding fields to Enums. Suppose we have an enumeration like:

enum NotificationColor { 
    YELLOW("yellow"),
    GREEN("green"),
    RED("red");

    private final String representation;

    public String toString() {
        return this.representation
    }
}

Can we still use == to compare the enumerated values or do we have to use .equals() since there are fields now? To answer this question, all we have to do is refer back to the source:

public final boolean equals(Object other) {
    return this==other;
}

The Enum#equals doesn’t consider fields, methods, or any attributes on an Enum to be relevant when comparing if one enumerated value is equal to another. It simply compares them using the equality operator. Therefore you can always use == to compare two enumerated values no matter what fields or methods are defined on Enum.