my dog learned polymorphism*
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 Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Comparator & Comparable" Watch "Comparator & Comparable" New topic
Author

Comparator & Comparable

Steven Gao Song
Ranch Hand

Joined: Oct 02, 2006
Posts: 78
Hi,
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: 2367
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: 3255
    
    2
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.

HTH,
Paul.


Enthuware - Best Mock Exams and Questions for Oracle/Sun 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: http://aspose.com/file-tools
 
subject: Comparator & Comparable
 
Similar Threads
Interface
Difference in between comparable and comparator interface
sorting of a list having bean object
difference between Comparator and Comparable interface
Sort a list