This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes how comparator works? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "how comparator works?" Watch "how comparator works?" New topic
Author

how comparator works?

Jayanth Mathavan
Greenhorn

Joined: Nov 10, 2005
Posts: 16
Hi,
I have a very basic question with Comparator. Please see the code below:

In the above code, I guess the compare() method in class AgeComparator is called for sorting the data. I would like to know from which part of the code, the compare() method is called.Basically how the flow of the above program is happening? Please help.

Thanks and Regards,
Jayanth Mathavan


Edit by mw: Added Code Tags.
[ August 14, 2007: Message edited by: marc weber ]
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

"Jayanth,"

Please check your private messages by clicking on the "My Profile" link near the top of the page.


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Michael Ku
Ranch Hand

Joined: Apr 20, 2002
Posts: 510
Arrays.sort(employee, new AgeComparator());
the Arrays class uses the AgeComparator to compare entries in the employee array 2 until it gets the order it wants.

If you run this in debug and place a breakpoint in the AgeComparator you will see it called over and over...
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

To see what's being compared and when, you could add the following to the compare method...

Employee e1 = (Employee)emp1;
Employee e2 = (Employee)emp2;
System.out.println("Comparing " + e1.getName() + " and " + e2.getName());
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
You could also take a look at the code of Arrays.sort, which comes with the JDK.


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
 
 
subject: how comparator works?
 
Similar Threads
Employee with same values is being added two times in HashSet
Descending order and associating Array Elements in sort method to another's elements
Sorting arraylist on the basis of object
comparator example needed
Difference between Comparable and Comparator