comparator interface

i would like to know more about comparator interface. why it is in java.util not in java.lang.

how it is different from comparable interface.

how compare() different from compareTo().

why implementing comparator second method equals() is optional unlike implementing compare() is mandotory
please advise
Who is Participating?
Margaret GreenCommented:
1. Comparable interface in java.lang is used to define the natural ordering on a class. A class can implement it only once. Comparator in java.util defines a total ordering on instances of a class. A Comparator implementing class can be separate class from the class it orders. A developer can create multiple Comparators for a class. That is, multiple orderings of of collection can be defined with separate Comparator implementations.

2. The Comparable interface method, compareTo() should throw a NullPointerException when null is given as the input. The Comparator interface compare() can accept a null value.

3. Comparable is implemented by a class that has a natural ordering among its member instances. Comparator is implemented to provide a total ordering on a class that may not have a natural ordering. There is only one natural ordering on instances of a class, the can be more than one total ordering of instances of a class.

4. Comparable should be consistent with equals. The equals method is specified by the class implementing the Comparable interface. A Comparator may be implemented by the class it defines a total ordering for, but it may also be implemented by some other class for the purpose of defining a total ordering on a target class. In the latter case, equals should be implemented because it will be comparing whether two Comparator instances are equal, that is they impose the the same total ordering.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.