• Post Reply Bookmark Topic Watch Topic
  • New Topic

compareTo method with the Comparator interface?  RSS feed

 
Shelby Simpson
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am confused to how the "compareTo()" method is able to be used in a class that implements Comparator which is a interface and has no "compareTo()" method. Here is an example of some working code that uses this method.



Thanks in advanced
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
We're calling name.compareTo(), so name is of some type that implements Comparable, such as String. Comparable has a compareTo() method.
 
manish ghildiyal
Ranch Hand
Posts: 136
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In code snippet, compareTo is being called on name..it means that Class of which name is a type must be implementing Comparable interface. Infact, we can also make FancyThing implement comparable and then call its version of compareTo in compare method.
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
manish ghildiyal wrote:In code snippet, compareTo is being called on name..it means that Class of which name is a type must be implementing Comparable interface.


I already said that. Please read the other responses before posting.

Infact, we can also make FancyThing implement comparable and then call its version of compareTo in compare method.


It's clear that the OP already knows that.
 
Shelby Simpson
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ah I see. Name which is a string object implements Comparable and that's how the compareTo is being used.

Thanks, I appreciate the help.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!