• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Comparable and Comparator

 
Sow
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Chap 7 states that:
Comparable has a single method : compareTo()
and
Comparator has only one method : Compare()

Pg 554 has a small code as follows:



My doubt is that is it okay to use compareTo method without implementing the comparable???
 
Prasanna Rajaperumal
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What exactly you mean by "Is it Okay". Is it legal?
Yes. You can either use comparable by not specifying a comparator while instantiating or you can chose to use a comparator without/with your objects implementing comparable.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15216
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are calling compareTo() on the object that is returned by one.getGenre().

The class of that object has a compareTo() method, otherwise this code wouldn't compile. It doesn't matter if that compareTo() method is there because the class implements Comparable or not.
 
Sow
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi ,

Based the two replies - can we say that compareTo() can be used with or without implementing the comparable. Correct me if i am wrong...

Thanks,
Sowmiya.
 
Peter Mularien
Author
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Sowmiya girish:
Based the two replies - can we say that compareTo() can be used with or without implementing the comparable. Correct me if i am wrong...

Sure you can, but keep in mind that without saying that your class implements Comparable, you will not be able to pass a class instance to a method expecting a parameter that "is-a" Comparable. For example, the version of Collections.max that takes a Comparable:

Hope that helps!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic