• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Devaka Cooray
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • Paul Clapham
Sheriffs:
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Saloon Keepers:
  • Tim Holloway
Bartenders:

Comparator & Comparable

 
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 2412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Enthuware Software Support
Posts: 4928
61
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What is the difference(or relation) between the Comparator and the Comparable interfaces?
 
"How many licks ..." - I think all of this dog's research starts with these words. Tasty tiny ad:
The new gardening playing cards kickstarter is now live!
https://www.kickstarter.com/projects/paulwheaton/garden-cards
reply
    Bookmark Topic Watch Topic
  • New Topic