File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Comparator's compare() method question 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 » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Comparator Watch "Comparator New topic
Author

Comparator's compare() method question

Sean Lim
Greenhorn

Joined: Oct 01, 2009
Posts: 10
Hi guys,

In chapter 7 form K&B's SCJP book there is a piece of code which I had a question on.


How does the compare() method determine which strings it uses as a, and as b?
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18486
    
  40

Sean Lim wrote:
How does the compare() method determine which strings it uses as a, and as b?


It doesn't. It is the sorting algorithm that determines which elements that it needs to compare -- and that is algorithm dependent.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Anbarasu Aladiyan
Ranch Hand

Joined: Jun 02, 2009
Posts: 182

from java documentation
the comparator is used to determine the order of the list

And,
order of the argument and its invocation are matters.

Both the codes will produce the same result.


A.A.Anbarasu
Sean Lim
Greenhorn

Joined: Oct 01, 2009
Posts: 10
Henry Wong wrote:
Sean Lim wrote:
How does the compare() method determine which strings it uses as a, and as b?


It doesn't. It is the sorting algorithm that determines which elements that it needs to compare -- and that is algorithm dependent.

Henry


Thanks Henry, but which algorithm is it using in the code posted? All I see is that it's using the Array's sort method and that it would be in natural order? But because it flipped the arguments it is actually in reverse natural order, as far as I can tell.

Thanks Anbarasu for pointing that out.
Rajeev Trikha
Ranch Hand

Joined: Jan 29, 2010
Posts: 85
Sean, whenever your Comparator is invoked it is going to reverse the collection because of the line return b.compareTo(a) If ascending order is required then a.compareTo(b) will be used.


Rajeev Trikha (SCJP 6)
Sean Lim
Greenhorn

Joined: Oct 01, 2009
Posts: 10
Rajeev Trikha wrote:Sean, whenever your Comparator is invoked it is going to reverse the collection because of the line return b.compareTo(a) If ascending order is required then a.compareTo(b) will be used.


Thanks, for clarifying that.
 
Consider Paul's rocket mass heater.
 
subject: Comparator's compare() method question
 
Similar Threads
Comparator interface
Searching Arrays and Collections
Comparator interface
sorting array
Object of static class