Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Comparator interface

 
swaraj gupta
Ranch Hand
Posts: 182
C++ Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is from KS and BB book, why it is getting possible for the class ReSortComparator to use compareTo() method of Comparable interface in compare() method, though ReSortComparator class doesn't implements it.
And whats actually happening at line 12 and why we have done so..?
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's calling the compareTo method of "String b". If you look at the String class API, you'll see that it implements Comparable.
 
Deepak Bala
Bartender
Posts: 6663
5
Firefox Browser Linux MyEclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That implementation is common when the object being compared is already a Comparable. Like Christophe says, String is already a Comparable
 
swaraj gupta
Ranch Hand
Posts: 182
C++ Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Christophe Verré and Deepak Bala thanks for your replies !!

1> I got from here that the Strings objects were compared. And as the String class already implements the Comparable interface, we can use the compareTo() method over its objects directly. Am i right... ?

2> What will happen internally when line #12 will be executed, I mean to say how the control will flow and which line will do what until the call returns?
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1> Yes.

2> The API of the sort method will give you an hint on how things are done. For more internal details, you can still look at the source of the Arrays class.
 
Deepak Bala
Bartender
Posts: 6663
5
Firefox Browser Linux MyEclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
swaraj gupta wrote:Christophe Verré and Deepak Bala thanks for your replies !!

1> I got from here that the Strings objects were compared. And as the String class already implements the Comparable interface, we can use the compareTo() method over its objects directly. Am i right... ?



Yep

swaraj gupta wrote:

2> What will happen internally when line #12 will be executed, I mean to say how the control will flow and which line will do what until the call returns?


The code flow would depend on Arrays.sort()'s internal implementation. Your ResortComparator will be called at sometime during the sorting process. The how, when, why of it is transparent to the caller.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic