Kamis, 10 Juli 2014

How to Compare Two Enum in Java - Equals vs == vs CompareTo






How do I compare two enum in Java? Should I use == operator or equals() method?
What is difference between comparing enum with == and
equals() method are
some of the tricky Java questions. Until
you have solid knowledge of Enum in Java, It can be difficult to answer these
question with confidence. By the way unlike comparing String in Java, you
can use both == and
equals() method to compare Enum, they
will produce same result because
equals() method of Java.lang.Enum internally
uses == to compare enum in Java.
Since every Enum in Java implicitly extends
java.lang.Enum ,and since equals() method is
declared final, there is no chance of
overriding equals method in user defined enum. If you are not just checking
whether two enum are equal or not, and rather interested in order of different
instance of Enum, than you can use compareTo() method of enum to
compare two enums.
Java.lang.Enum implements Comparable interface and
imple
ments
compareTo() method. Natural order of enum is
defined by the order they are declared in Java code and same order is returned
by
ordinal() method.






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{
RECTANGLE, SQUARE, CIRCLE, TRIANGLE;
}

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,
s
ame 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





 






























Source:http://javarevisited.blogspot.com/2013/04/how-to-compare-two-enum-in-java-equals.html

1 komentar:

  1. Nice explanation.
    Thanks,
    https://www.flowerbrackets.com/difference-between-equal-operator-vs-equals-method-java/

    BalasHapus