aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Comparable and Comparator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Comparable and Comparator" Watch "Comparable and Comparator" New topic
Author

Comparable and Comparator

Sow
Greenhorn

Joined: Aug 16, 2007
Posts: 12
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

Joined: Aug 28, 2007
Posts: 9
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

Joined: Aug 16, 2005
Posts: 14345
    
  22

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.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Sow
Greenhorn

Joined: Aug 16, 2007
Posts: 12
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

Joined: Sep 06, 2007
Posts: 84
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!


Author, Spring Security 3 (the Book), Packt Publishing, 2010
SCJP, OCP
 
 
subject: Comparable and Comparator