Check the contractual obligations of the comparator interface

Source: Internet
Author: User
Tags comparison sort

The Java.util.Comparator interface is easy to implement and use, but some parts of the comparator API document should be read carefully.

Classes that implement the comparator interface can be passed to a sort method such as Collections.sort. They can also be used by maps or set classes to ensure that the elements in a map or set are always sorted in some order. TreeSet and TreeMap are such classes.

In the comparator interface, there is only one method that needs to be implemented:

int compare (Object o1,object O2);

Returns a negative number if the O1 is less than O2, returns a positive number if the O1 is greater than O2, and returns 0 if they are equal;

These are all things that are usually done in order to complete the comparison, but there are other obligations in the contract of the comparator interface.

First of all, the Compare method must be symmetrical, meaning that compare (a,b) Returns the result to be opposite to compare (B,a). The opposite result means that either the returned value has a different positive or negative number, or is 0. Note that compare (A,B) returns 4 and compare (B,a) returns-2 is legal. It is often possible to throw an exception in a method, and to throw an exception in this method is symmetric. If a classcastexception exception is thrown when compare (A,b) is invoked, a B,a exception must also be thrown when calling compare (ClassCastException).

Consider the following code fragment:

public int compareTo(Object o1, Object o2) {
if(o1 instanceof Long) {
Long ln = (Long)o1;
return ln.compareTo(o2);
} else {
return 0;
}
}

If A is a new Long (5) and B is "Text", then the execution compare (O1,o2) throws a classcastexception in the Java.lang.Long CompareTo method, and executes compare (O2,O1 ) will return 0 (translator Note: The original text here is compare (O1,O2), according to the context, should be compare (O2,O1)).

Second, any comparator you are prepared to reuse must be serializable. The TreeSet and TreeMap classes store comparator For comparison purposes, so for these two classes to be serialized, the comparator they use must also be serializable.

Third, if there are a number of comparison methods, then comparator should implement the Equals method. It is common for developers to create comparator that have multiple forms of comparison, such as:

import java.util.Comparator;
public class ExampleComparator {
private int type;
public ExampleComparator(int i) {
this.type = i;
}
public int compareTo(Object o1, Object o2) {
if(type == 1) {
// one type of comparison
....
} else
if(type == 2) {
// another form of comparison
....
}
}
}

The comparator interface, commonly used by the Collections.sort method, is an important part of Java that needs to be understood because it has some important contractual obligations that are often overlooked.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.