File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "how comparator works?" Watch "how comparator works?" New topic

how comparator works?

Jayanth Mathavan

Joined: Nov 10, 2005
Posts: 16
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

Joined: Aug 31, 2004
Posts: 11343


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
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

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

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
I agree. Here's the link:
subject: how comparator works?
It's not a secret anymore!