Wednesday 10 April 2013

Compare Two Enum in Java - Equals, == ,CompareTo

Leave a Comment

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.

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.

 Equals from java.lang.Enum class


public final boolean equals(Object other)
{ 
    return this==other; 
}


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

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



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

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

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; 
}


0 comments:

Post a Comment