Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how comparator works?

 
Jayanth Mathavan
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"Jayanth,"

Please check your private messages by clicking on the "My Profile" link near the top of the page.
 
Michael Ku
Ranch Hand
Posts: 510
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could also take a look at the code of Arrays.sort, which comes with the JDK.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic