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{
}
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){
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?
Java Books
Return to : Java Programming Hints and Tips All the site contents are Copyright © www.erpgreat.com
and the content authors. All rights reserved.
|