java.lang.Comparable and java.lang.Comparator can anyone explain the difference between the 2 interfaces. Comparable has a method compareTo(Object o) So any class which supports sorting of it's objects w'd probably implement this as well. Now comparator has a compare(Object o1, Object o2) Since this is taking 2 objects i don't expect it to be a part of the class which wants to support sorting (itself). thanks, karthik.
Your question seems to answer itself. But if it would help to have an example, consider that String impements Comparable, and has a compareTo(Object) method that is case-sensitive, as is its equals() method. However, sometime you need to do case-insensitive comparison of strings. So String provides String.CASE_INSENSITIVE_ORDER, an implementation of Comparitor that provides a case-insensitive compare(Object, Object) method. (Since the case-insensitive comparitor is not consistent String's equals method, you have to be careful about where you use it.)
hi, I was just (5 minutes ago) studying this It goes like this: If you are designing your OWN classes and there is a need for comparing, you might prefer to use the natural comparison method by implementing Comparable here is code I just had to copy from my editor
Getal = dutch for Number (I couldn't use Number as classname could I ) But what if you get a class that you don't have the source code of and you need to sort the items ? Or what if the class has allready implemented Comparable, but you want to sort the class on another value ? then you might choose for the Comparator method! You just create a new Class and implement the compare() method; Usually the equals method inherited from Object or whatever is just fine here is an example
The AlphabeticComparator class does actually the same as the public static final Comparator CASE_INSENSITIVE_ORDER from String Thanks for pointing that out John!! I didn't knew it had that field anyway, karthik hope I could help you Dave
[This message has been edited by Dave Van Even (edited October 14, 2001).] [This message has been edited by Dave Van Even (edited October 14, 2001).]
Dave Van Even
Joined: Jul 19, 2001
damn.. half my code gets transformed into garbage be because the UBB code tag doesn't translate to HTML codes hope you get the idea
subject: Why 2 interfaces Comparable and Comparator?