Java comparators: Comparable and comparator

Source: Internet
Author: User

First, comparable interface

1, public interface comparable{

public int CompareTo (Object other);

}

2. When this object is less than, equal to, or greater than the other object, a value less than, equal to, or greater than 0 is returned accordingly.

3, if the object can not be compared, throw classcastexception

4, CompareTo () The order of definition is the natural order of the class, that is, this sort is most natural to the object of the class.

5, Equals () defines a natural equality relationship, two objects are equal, and returns ture.

6, many classes: String, Date, Java.io.Fil, and wrapper class all implement this interface.

Second, comparator interface

1, public interface comparator<t>{

public int Compare (T O1, To2);

Boolean equals (Object obj);

}

2, the class that does not implement the comparable interface, or the class that implements the comparable interface does not want to use CompareTo () to compare, you can use the comparator interface to compare (we need to implement this interface), and in

The order in which compare () is defined is called the comparer order.

3, for the overall sorting of the collection. Forces the overall ordering of elements of certain collection objects, such as TreeMap, TreeSet, SortedMap, and SortedSet, which can be assigned a comparer to these collection objects.

Third, where to need comparator

1. Classes that need to be compared, use comparable between the same class objects and are implemented by this class, not homogeneous or overall sort using comparator.

2. The set to be sorted

Java comparators: Comparable and comparator

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.