Summary of Java two comparators

Source: Internet
Author: User

"Comparable and comparator source"

java.lang.Comparable      Public Interface Comparable<t> {    publicint  comparato (T o);} ------------------------------------------------------------------java.util.Comparatorpublic  Interface comparator<t> {    int  compare (T o1,t O2);     Boolean equals (Object obj);}

"Comparable Interface"

If a class implements the comparable interface, it means that the class supports sorting. Assuming there is a list (or array) of objects for the class that implements the comparable interface, the list (or array) can be sorted by Collections.sort (or Arrays.sort).

"Comparator Interface"

We need to control the order of a class, which does not support ordering (that is, the comparable interface is not implemented). So, we can create a comparer for this class, which only needs to implement comparator. If a class implements the comparator interface, it must implement the compare (T o1,t O2) method, but it does not necessarily implement the Equals (Object obj) method;

"Comparison between the two"

1.Comparable is a sort interface; If a class implements the comparable interface, it means "this class supports sorting" and comparator is the comparator; if we need to control the order of a class, we can create a "comparer for that class" to sort by.

The 2.Comparable corresponds to an "internal comparator", while the comparator is equivalent to an "external comparator".

Summary of Java two comparators

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.