| Author |
Comparable and Comparator Interface use
|
sumanta panda
Ranch Hand
Joined: Jun 23, 2008
Posts: 224
|
|
Dear All,
Please suggest in which real life project senario we should go with Comparable and Comparator interface?
Thanks!
Sumanta Panda
|
 |
Paul Sturrock
Bartender
Joined: Apr 14, 2004
Posts: 10336
|
|
|
We would use them when we want to compare objects with one another. So any time you have more than one object of the same type you need to compare.
|
JavaRanch FAQ HowToAskQuestionsOnJavaRanch
|
 |
sumanta panda
Ranch Hand
Joined: Jun 23, 2008
Posts: 224
|
|
Dear Paul Sturrock,
Thanks for your response.Could you please tell me in which senario we should go with comparable and which senario we should go with comparator interface.
Thanks!
Sumanta Panda
|
 |
Paul Clapham
Bartender
Joined: Oct 14, 2005
Posts: 16479
|
|
The first link returned by Google for keywords "java comparable tutorial":
Object Ordering (The Java™ Tutorials)
|
 |
Adam Stojanowski
Greenhorn
Joined: Jul 03, 2010
Posts: 2
|
|
Implementing Comparable lets object compare itself to other objects of the same class, it provides natural ordering fo objects. If you implement Comparator you create small class which you can use to compare objects of other classes, you are injecting ability to order from outside.
Comparable provides just one compareTo() method which means that you will have only one way of comparing objects. In most cases its enough, but sometimes you will want to compare objects of your class in many ways (for example: 'normal' way of comparing Person objects could use names, but in specific case you could need comparing by age or by height) - in such cases Comparator is better, you can have separate class for each criteria.
Sometimes you have to compare objects of class which doesn't implement Comparable and cannot be chanched - in such cases the only way is using Comparator.
To sum up: Use Comparable in simple cases where you can control comparable class. If you cannot modify class or you need more than one way of comparing - use Comparator.
|
 |
 |
|
|
subject: Comparable and Comparator Interface use
|
|
|