Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparator best practice

If I implement a custom comparator is it considered good practice to overide equals besides compare?
Additionally is there a defined contract for a Comparator?

like image 619
Jim Avatar asked Oct 04 '12 09:10

Jim


People also ask

What is the comparator method?

Method 2: Using comparator interface- Comparator interface is used to order the objects of a user-defined class. This interface is present in java. util package and contains 2 methods compare(Object obj1, Object obj2) and equals(Object element). Using a comparator, we can sort the elements based on data members.

What should a comparator return?

It returns a positive value if obj1 is greater than obj2. Otherwise, a negative value is returned. By overriding compare( ), you can alter the way that objects are ordered. For example, to sort in a reverse order, you can create a comparator that reverses the outcome of a comparison.

When would you use a comparator instead of implementing comparable?

To summarize, if sorting of objects needs to be based on natural order then use Comparable whereas if you sorting needs to be done on attributes of different objects, then use Comparator in Java.

What is difference between comparator and comparable?

Comparable interface is used to sort the objects with natural ordering. Comparator in Java is used to sort attributes of different objects. Comparable interface compares “this” reference with the object specified. Comparator in Java compares two different class objects provided.


1 Answers

The contract of Comparator is defined in its javadoc. In particular:

Caution should be exercised when using a comparator capable of imposing an ordering inconsistent with equals to order a sorted set (or sorted map). Suppose a sorted set (or sorted map) with an explicit comparator c is used with elements (or keys) drawn from a set S. If the ordering imposed by c on S is inconsistent with equals, the sorted set (or sorted map) will behave "strangely." In particular the sorted set (or sorted map) will violate the general contract for set (or map), which is defined in terms of equals.

Typically, if 2 objects are equal from an equals perspective but not from a compareTo perspective, you can store both objects as keys in a TreeMap. This can lead to un-intuitive behaviour. It can also be done on purpose in specific situations.

For example, this answer shows an example where it is desirable that equals and compareTo be inconsistent.

like image 82
assylias Avatar answered Oct 14 '22 12:10

assylias