How To Compare 2 Enum Inwards Coffee - Equals Vs == Vs Compareto

How do I compare 2 enum inward Java? Should I purpose == operator or equals() method? What is divergence betwixt comparing enum amongst == together with equals() method are exactly about of the tricky Java questions. Until yous convey corporation noesis of Enum inward Java, It tin terminate last hard to respond these enquiry amongst confidence. By the way unlike comparing String inward Java, you tin terminate purpose both == together with equals() method to compare Enum, they volition create same trial because equals() method of Java.lang.Enum internally uses == to compare enum inward Java. Since every Enum inward Java implicitly extends java.lang.Enum ,and since equals() method is declared final, there is no guide chances of overriding equals method inward user defined enum. If yous are non exactly checking whether 2 enum are equal or not, together with rather interested inward club of unlike instance of Enum, than yous tin terminate use compareTo() method of enum to compare 2 enums. Java.lang.Enum implements Comparable interface together with implements compareTo() method. Natural club of enum is defined past times the club they are declared inward Java code together with same club is returned past times ordinal() method.

Comparing Enum amongst equals together with ==

equals() method is declared concluding within 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 at that topographic point are subtle difference when yous compare enum amongst == together with equals method, which stems from ==  (equality operator) beingness operator together with equals() beingness method. Some of these points are already discussed inward difference betwixt equals together with == inward Java, but nosotros volition encounter them hither amongst abide by to comparing Enums inward Java.

1) Using == for comparing Enum tin terminate forbid NullPointerException
This i is slow to guess, but same fourth dimension render worth of money. If yous compare whatsoever Enum amongst null, using == operator, it volition trial inward false, but if yous purpose equals() method to do this check, yous may acquire NullPointerException, unless yous are using calling equals inward correct way equally shown in how to avoid NullPointerException inward Java. Look at below code, hither nosotros are comparing an unknown Shape object amongst 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 trial = unknown == circle; //return false trial = unknown.equals(circle); //throws NullPointerException
I concord this tin terminate last avoided past times only comparing known to unknown i.e. circle.equals(unknown), but this is i of the most common coding fault Java programmers make. By using == to compare enum, yous tin terminate completely avoid it.

2) == method provides type security during compile time
Another wages of using == to compare enum is, compile fourth dimension safety. Equality or == operator checks if both enum object are from same enum type or non at compile fourth dimension itself, spell equals() method volition equally good render fake but at runtime. Since it's ever ameliorate to discovery errors at compile time, == scores over equals inward instance of comparing enum. If yous are using Eclipse or Netbeans, yous tin terminate discovery these fault equally before long equally yous type. By the way Netbeans equally good shows alert when yous telephone outcry upward equals() method on 2 incomparable types, but that is completely IDE specific.

3) == should last faster than equals method
This is to a greater extent than from mutual sense, using operator should last a touching on faster than calling method, together with than using operator. Though I believe modern JIT compiler mightiness inline equals() method, when yous compare 2 enums inward Java. Which agency this would non last big divergence inward price of performance.But, without whatsoever smartness from compiler or JVM, I recollect == should ever last touching on faster.

Comparing Enums amongst compareTo method

When nosotros tell comparing enum, it's non ever checking if 2 enums are equal or not. Sometime yous take away to compare them for sorting or to adapt them inward a especially order. We know that nosotros tin terminate compare objects using Comparable together with Comparator inward Java together with enum is no different, though it provides additional convenience. Java.lang.Enum implements Comparable interface together with it's compareTo() method compares alone same type of enum. Also natural club of enum is the club inward which they are declared inward code. As shown on 10 examples of Enum inward Java, same club is equally good maintained past times ordinal() method of enum, which is used past times EnumSet together with 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 yous expect in conclusion line, it's using ordinal to compare 2 enum inward Java.

That's all on How to compare 2 enum inward Java together with divergence betwixt == together with equals to compare 2 enums. Though using equals() to compare object is considered Java best practice, comparing Enum using == is ameliorate than using equals. Don't forget ordinal() together with compareTo() methods, which is equally good telephone commutation to acquire natural club of Enum during comparison.




Recommended Reading on Java Enum

If yous desire to larn to a greater extent than almost Enum, I advise reading next Java books. Books are best resources to larn deep almost whatsoever topic together with I personally follow them equally well. Enumeration types chapter from Thinking inward Java is especially useful. 



Thinking inward Java (4th Edition) By Bruce Eckel

Java 5.0 Tiger: H5N1 Developers notebook
Effective Java past times Joshua Bloch

 

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

0 Response to "How To Compare 2 Enum Inwards Coffee - Equals Vs == Vs Compareto"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel