Paul
Paul
I'm not too sure what you're getting at in your second question below (the two approaches that you've outlined are quite different) but the following might help. If you define a natural ordering for a class by implementing the Comparator interface, you can add instances of the class to a TreeSet or as the keys in a TreeMap and the natural ordering will be used to sort those items.
If a class does not implement Comparable, you cannot add instances of that class to TreeSet or TreeMap unless you also implement a Comparator which defines an ordering for instances of that class.
Paul
Paul, wouldn't that be Comparable?
Anyway, giving my two cents, notice that when a class implements
Comparable, it is comparing itself against another object, while when
a class implements Comparator, it is comparing two other objects. One
example from the Java default library, the class String implements
Comparable, because you can call "abc".compareTo("def") and get the
natural ordering of the strings (in this case, lexicographical order).
Now take a look at Collator, which implements Comparator, and is used
to compare two strings (i.e. not itself against another Collator, but
two different objects), so you can use:
Collator.getInstance().compare("abc", "def") and you will get a
different order (in this case the alphabetical order, i.e. ignoring
case, so A < b < C).
Hope this helps,
Jonatan
--
Jonatan Schroeder, MSc.
Teaching Assistant, PhD Student
UBC - Computer Science
jon...@cs.ubc.ca - http://www.cs.ubc.ca/~jonatan
"He who asks is a fool for five minutes, but he who does not ask
remains a fool forever." -- Chinese proverb
"Computer science is no more about computers than astronomy is about
telescopes." -- Edsger W. Dijkstra
Paul