• Post Reply Bookmark Topic Watch Topic
  • New Topic

Comparator's compare() method question  RSS feed

 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
author
Sheriff
Posts: 23485
138
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
 
Ranch Hand
Posts: 182
Chrome Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Sean Lim
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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.
 
Ranch Hand
Posts: 85
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Sean Lim
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!