what's the difference between comparable and comparator interface.
> what's the difference between comparable and comparator interface.
Comparable interface shows that the class knows how to compare ITSELF
against another class.
Comparator interface allows a single class know how to compare two
classes which (typically) are not the same type as the comparator.
Its about moving the responsibility for doing the comparison from the
class that is being compared, to another class who's sole responsibility
is to be the comparator.
> what's the difference between comparable and comparator interface.
Something that's Comparable knows how to compare itself to others
(presumably of the same class). How it does so is built into the class.
For example, Strings compare themselves alphabetically (well, by character
value, anyway). A Comparator can compare two other objects by whatever
criterion the Comparator chooses. For example, it might compare Strings by
their length.
HTH,
Michiel
Oscar kind - 20 Feb 2005 14:24 GMT
In comp.lang.java.help Michiel Konstapel <usenet@konstapel.nl> wrote:
>> what's the difference between comparable and comparator interface.
>
[quoted text clipped - 4 lines]
> criterion the Comparator chooses. For example, it might compare Strings by
> their length.
The Comparable interface is (IMO) best used to implement a natural order
for lists of elements of the class. For example the low-to-high order of
numbers represented by the Integer class. This ties in nicely with the
order used by the variants of TreeSet, TreeMap, Arrays.sort() and
Collections.sort() where no Compataror is specified.
The Comparator interface is then used to create exotic orders, where
exotic is anything not implemented by the Comparable interface. This also
means the most obvious order for elements if a class doesn't implement
Comparable, though a subclass may sometimes be a better choice then.

Signature
Oscar Kind http://home.hccnet.nl/okind/
Software Developer for contact information, see website
PGP Key fingerprint: 91F3 6C72 F465 5E98 C246 61D9 2C32 8E24 097B B4E2