Another blog:

It is easier to write an incorrect program than understand a correct one.

Thursday, April 28, 2011

Java sorting - comparable v comparator

int objOne.compareTO(objTwo) – A Comparable interfaced class must contain a method called compareTo to compare two objects (one being the object on which it is called and the other being passed as a paramater)int compare(objOne, objTwo) – A Comparator is a class in its own right, which implements the Comparator interface; that means it must contain a method called compare (two objects as parameters)
Return Values -
negative – if objOne < objTwo
zero – if objOne = objTwo
positive – if objOne > objTwo
Return Value -
same as Comparable
Only one sort sequence can be createdMany sort sequences can be created
You must modify the class whose instances you want to sortYou build a separate class from the class whose instances you want to sort
Implemented frequently in the API by : String, Wrapper Classes, Date, CalendarMeant to be implemented to sort instances of third-party classes
If you want to sort a collection using its comparable interface, you simply call the static Collections.sort method on it … so if we had an ArrayList called Animal which implemented Comparable, we could write:
To sort a collection using a Comparator class, you need to pass an extra parameter into the Collections.sortmethod – that parameter being an instance of a Comparator object. Thus:
Collections.sort(Animal, new ByBreed());

1 comment:

  1. Wonderful post and that too in tabular format excellent for quick revision just to add while using comparable interface in Java and overriding compareTo method its worth noting that compareTo must be compatible with s equals method in Java i.e. if two objects are equal via equals method compareTo method must return "0" for them, failing this may result in some subtle bug when you store those objects in collection class like TreeSet and TreeMap.

    Source: How to use Comparator and Comparable in Java