Difference Between Comparable And Comparator Interface

Explain what are the difference between Comparable And Comparator Interface in java?

The difference is quite obvious . Comparable is interface that is implemented by a class of object that have to be sorted.

For example:

class SortObject implements Comparable{
 public int compareTo(Object obj){

 }
}

and for sorting an array of SortObjects

Arrays.sort(sortObjectsArray); //this is enough

Comparator is mainly used to override a method compare. But it is more generic and can be used to sort any "collection" (of appropriate type) class 

CompClass implements Comparator{  public int compare(Object obj1,Object obj2){
    //make a cast of obj1 and obj2 for comparison.
   // return compare result.
 }
}

Usage will be like:

Arrays.sort(sortArray,new CompClass());

If you are not careful in using the Comparator it can result in ClassCastException at runtime.

Do you have a Java Problem?
Ask It in The Java Forum

Java Books
Java Certification, Programming, JavaBean and Object Oriented Reference Books

Return to : Java Programming Hints and Tips

All the site contents are Copyright © www.erpgreat.com and the content authors. All rights reserved.
All product names are trademarks of their respective companies.
The site www.erpgreat.com is not affiliated with or endorsed by any company listed at this site.
Every effort is made to ensure the content integrity.  Information used on this site is at your own risk.
 The content on this site may not be reproduced or redistributed without the express written permission of
www.erpgreat.com or the content authors.