Rajinder Menu

Using Comparable interface to compare objects of two different types.



Comparable interface and its compareTo() method is generally used to compare objects in their natural order and for comparing instances of same class.

But this is not a restriction, only a guideline set by contract of Comparable.  We can still write code that compares objects of two different types using compareTo() as shown below:

MyClass.java
public class MyClass implements Comparable<String>{

  int i;
  public MyClass(int i){
    this.i=i;
 }

  /*
   Here we are using compareTo() to compare objects of two different types - MyClass (represented by 'this') and String.
 */
 @Override
 public int compareTo(String str){
   int intValue=Integer.parseInt(str);

  if(this.i > intValue)
     return 1;
  if (this.i < intValue)
     return -1;
  else
    return 0;
 }
}

Test.java
public class Test{
public static void main(String args[]){

   MyClass myClass= new MyClass(1);

/*Using compareTo() to compare objects of two different types - MyClass and String.*/
  if(myClass.compareTo("10")<0)
      System.out.println("myClass is smaller.");
else if(myClass.compareTo("10")>0)
     System.out.println("myClass is greater.");
else if(myClass.compareTo("10")==0)
    System.out.println("Both equals!!!");
  }
}


Here in compareTo() method of MyClass, we are comparing two objects - one of type MyClass and other of type String with output:


Also there is no natural order between MyClass and String instances as natural order exists between the objects of same type.

Usually we throw ClassCastException in compareTo() when we do not want to it to compare objects of different types as:


public class MyClass implements Comparable<String>{
..
public int compareTo(String str){
...
if(!(obj instanceof MyClass)){
       throw new ClassCastException("Not Comparable Objects!");   // will throw exception
    }
}


and with the use of generic form of Comparable we even do not need to throw ClassCastException as types will be checked at compile time.


public class MyClass implements Comparable<MyClass>{
  public int compareTo(String str){  // will throw error at compile  time
   ...
 }
}




I would like to know your comments and if you liked the article then please share it on social networking buttons.


No comments:

Post a Comment