Rabu, 28 Juli 2021

How to Compare Two Enum in Java? Equals vs == vs CompareTo Example

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 enums are equal or not, and rather interested in the order of different instances of Enum, then you can use compareTo() method of enum to compare two enums. 

Lorem ipsum is simply dummy text of the printing and typesetting industry.

Comments


EmoticonEmoticon