GeeCON Prague 2014*
The moose likes Beginning Java and the fly likes Collections Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Collections" Watch "Collections" New topic
Author

Collections

Muhammad Usman
Greenhorn

Joined: Nov 18, 2001
Posts: 29
hello to all,
while studying the collection class topic, i have come accross the term " comparator".
what does it mean,
can any body tell me.
thnaks
Cindy Glass
"The Hood"
Sheriff

Joined: Sep 29, 2000
Posts: 8521
When you go to sort something - what order should in result in?
The thing that determines what comes first and what next etc., is the comparator. Any class which implements the Comparator interface can be used to compare things using the compare() method that is promised by the interface.
If you are just sorting numbers or characters, there is an obvious "natural order" to them, but if you are sorting objects that themselves may consist of lots of references to other objects - well it gets much more confusing.
In the end even the most complicated sort comes down to looking the objects two at a time and deciding which is first. A Comparator provides the rules for how to figure out which is first - or if they compare as exactly the same.
If you create a class which is a Comparator (it implements the Comparator interface), you have the opportunity to define the ordering rules for this class yourself. However, in the end you need to make sure that the basic rules of logic prevail. Two things should never compare as exactly the same unless you can use the .equals method on them and it will result in "true".
[ March 13, 2002: Message edited by: Cindy Glass ]

"JavaRanch, where the deer and the Certified play" - David O'Meara
 
 
subject: Collections