Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Comparator & Comparable

 
Steven Gao Song
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3776
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic