File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Comparator & Comparable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Comparator & Comparable" Watch "Comparator & Comparable" New topic

Comparator & Comparable

Steven Gao Song
Ranch Hand

Joined: Oct 02, 2006
Posts: 78
I find that Interface Comparator and Comparable both
have the method to compare. Who can tell me what the
difference between them?
Thank you.
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2398
Comparable is an interface that a class can implement.

However, in order to use Comparable, you have to have access to the source code of the class.

The Comparator interface allows us to define a comparison between two objects when we may not have access to the source code.

Another use of the Comparator interface is that you can use it in conjuction with a Collection to sort the Collection in any way you want without having to change the class definition of the objects in the Collection.
Paul Anilprem
Enthuware Software Support
Ranch Hand

Joined: Sep 23, 2000
Posts: 3635
Comparable - Something that can be compared with another.
Comparator - Something that can compare two things.

If you understand the concept (it really is just the meaning of the two english words), the rest will be easy.

1. Comparable has compareTo() method that takes only one argument (the object with which 'this' object has to be compared) and Comparator has compare() method that takes two arguments (the objects that need to be compared.)

2. When a class knows how its objects can be compared, it implements Comparable. When *you* want to compare two objects *your* way (instead of the class's implementation), you create a new class that implements a Comparator and pass the two objects to its compare method.


Enthuware - Best Mock Exams and Questions for Oracle Java Certifications
Quality Guaranteed - Pass or Full Refund!
wise owen
Ranch Hand

Joined: Feb 02, 2006
Posts: 2023
What is the difference(or relation) between the Comparator and the Comparable interfaces?
I agree. Here's the link:
subject: Comparator & Comparable
jQuery in Action, 3rd edition