How To Compare 2 Enum Inwards Coffee - Equals Vs == Vs Compareto
How do I compare ii enum inwards Java? Should I purpose == operator or equals() method? What is divergence betwixt comparing enum amongst == as well as equals() method are approximately of the tricky Java questions. Until yous convey company noesis of Enum inwards Java, It tin last hard to reply these query amongst confidence. By the way unlike comparing String inwards Java, you tin purpose both == as well as equals() method to compare Enum, they volition create same final result because equals() method of Java.lang.Enum internally uses == to compare enum inwards Java. Since every Enum inwards Java implicitly extends java.lang.Enum ,and since equals() method is declared final, there is no peril of overriding equals method inwards user defined enum. If yous are non exactly checking whether ii enum are equal or not, as well as rather interested inwards guild of unlike instance of Enum, than yous tin use compareTo() method of enum to compare ii enums. Java.lang.Enum implements Comparable interface as well as implements compareTo() method. Natural guild of enum is defined past times the guild they are declared inwards Java code as well as same guild is returned past times ordinal() method.
Comparing Enum amongst equals as well as ==
equals() method is declared in conclusion within java.lang.Enum, so risk of overriding equals method.
Here is the code of equals from java.lang.Enum class
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 == as well as equals method, which stems from == (equality operator) existence operator as well as equals() existence method. Some of these points are already discussed inwards difference betwixt equals as well as == inwards Java, but nosotros volition come across them hither amongst honour to comparing Enums inwards Java.
1) Using == for comparing Enum tin foreclose NullPointerException
This 1 is slowly to guess, but same fourth dimension furnish worth of money. If yous compare whatsoever Enum amongst null, using == operator, it volition final result inwards false, but if yous purpose equals() method to do this check, yous may acquire NullPointerException, unless yous are using calling equals inwards correct way every bit shown in how to avoid NullPointerException inwards 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 final result = unknown == circle; //return false final result = unknown.equals(circle); //throws NullPointerExceptionI grip this tin last avoided past times only comparing known to unknown i.e. circle.equals(unknown), but this is 1 of the most common coding mistake Java programmers make. By using == to compare enum, yous tin completely avoid it.
2) == method provides type security during compile time
Another payoff 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 too render fake but at runtime. Since it's e'er amend to notice errors at compile time, == scores over equals inwards representative of comparing enum. If yous are using Eclipse or Netbeans, yous tin notice these mistake every bit before long every bit yous type. By the way Netbeans too shows alarm when yous telephone phone equals() method on ii 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 affect faster than calling method, as well as than using operator. Though I believe modern JIT compiler mightiness inline equals() method, when yous compare ii enums inwards Java. Which agency this would non last big divergence inwards price of performance.But, without whatsoever smartness from compiler or JVM, I holler upwards == should e'er last affect faster.
Comparing Enums amongst compareTo method
When nosotros tell comparing enum, it's non e'er checking if ii enums are equal or not. Sometime yous postulate to compare them for sorting or to accommodate them inwards a specially order. We know that nosotros tin compare objects using Comparable as well as Comparator inwards Java as well as enum is no different, though it provides additional convenience. Java.lang.Enum implements Comparable interface as well as it's compareTo() method compares exclusively same type of enum. Also natural guild of enum is the guild inwards which they are declared inwards code. As shown on 10 examples of Enum inwards Java, same guild is too maintained past times ordinal() method of enum, which is used past times EnumSet as well as 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 await in conclusion line, it's using ordinal to compare ii enum inwards Java.
That's all on How to compare ii enum inwards Java as well as divergence betwixt == as well as equals to compare ii enums. Though using equals() to compare object is considered Java best practice, comparing Enum using == is amend than using equals. Don't forget ordinal() as well as compareTo() methods, which is too fundamental to acquire natural guild 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 as well as I personally follow them every bit well. Enumeration types chapter from Thinking inwards Java is specially useful.
Thinking inwards Java (4th Edition) By Bruce Eckel
Java 5.0 Tiger: Influenza A virus subtype H5N1 Developers notebook
Effective Java past times Joshua Bloch
Further Reading
Java Fundamentals, Part 1 as well as 2
Core Java For the Impatient - Covers Java SE 8
Java Fundamentals: The Java Language
Komentar
Posting Komentar