The compare method returns a int which can be a negative,positive or a 0.
Example: class Example implements comparator {
public int compare(Object A,Object B) {
return ObjA.compareTo(Objb);
}
}
If 0 is returned ObjA = Objb
If -ve is returned ObjA < ObjB
If +ve is returned ObjA > ObjB
So it actually uses a compareTo method internally for sorting.The comparator interface is used if you would want to sort a collection in multiple ways.
It can be useful if you want to sort the objects. Sort algorithms generally work by comparing pairs of objects to see what order they should be in (the clever parts of the algorithm are deciding which objects to compare and what to do then - e.g. a bubble sort compares adjacent pairs and swaps them if they're in the wrong order, until there are no more to swap). So all they need is a method to tell them how to compare two objects - that's what Comparator (and Comparable) supplies.
Who will use? Anyone who wants to sort a collection. It is used implicitly if the objects are in a TreeSet where you MUST implement comparable interface for the objects. How does the system compare? For numeric variables then sorting is obvious, if they are characters, they will be sorted by their ASCII codes. Hope I have answered your question clear enough.
Joseph
Squanch that. And squanch this tiny ad:
free, earth-friendly heat - a kickstarter for putting coin in your pocket while saving the earth