Can some one help me with this Topic.I am having a lot of trouble understanding this topic. What is the main difference between the two and how are they implemented specially comparator. I undertand sort() uses comparable to sort out data..
I cant understand the differencemention in K&B
- What do you mean when you say you must modify the class incase of Comparable and build a sepatate class in case of Comparator
-Only one sequence is created in Comparable and many sequnce in Comprator.
Can some one give some examples or links which can make this whole topic clearer. Have spent ages on it and still can't understand anything.
How come one is in java.lang while the other in java.util
The future belongs to those who believe in the beauty of their dreams.Dream BIG!
There is another good text on Comparable&Comparator in theCollections Tutorial. But the K&B book explains it very good. Just try to sort something in different ways and you'll get the idea and see the difference.
I know how you feel - I learned from the same book - cause this topic confused me as well for a long time. So I decided to represent this to myself graphically.But I cannot post that because I did it in book. But let me help you understand it: -first of all lets play a little word-game. It will help you remember it easier. First, you say class is Comparable so for me it indicates that this class is self-comparable, or it is able-to-compare-it-self to some other object. It is self compared to or as it's method says compareTo(Object o). Second, you say class is Comparator because it is comparing objects of other class. So what it do is to, as it's method says, compare(Object o1, Object o2). Remember that Comparator itself is not compared to anything, it just compare(...)-s two objects of some other class. Comparable --> able-to-compares-itself compareTo(Object o) Comparator --> compares two other objects compare(Object o1, Object o2)
-second Comparable is in lang package because it is kinda natural that classes have such a behavior by themselfs and lang package doesn't have to be imported(this is my opinion don't take it as something generally known), and Comparator is in util cause it is kinda part of everyday work which includes Collections Framework that are in the same package...
third here is some example for you:
hope this helps
[ April 23, 2008: Message edited by: Ivan Ivanic ] [ April 23, 2008: Message edited by: Ivan Ivanic ]