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 implements 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.
Read more »

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

Posting Komentar