The difference between comparator and comparable in Java

Source: Internet
Author: User

1, comparable code is as follows:

 Public Interface Comparable<t> {    publicint  compareTo (T o);}

2, comparator code is as follows

 Public InterfaceComparator<t> {    intCompare (t O1, T O2); Booleanequals (Object obj); //the method after jdk1.8    defaultComparator<t>reversed () {returnCollections.reverseorder ( This); }    defaultComparator<t> thencomparing (comparator<?SuperT>Other )        {Objects.requirenonnull (other); return(Comparator<t> & Serializable) (c1, C2) {            intres =Compare (c1, C2); return(res! = 0)?Res:other.compare (c1, C2);    }; }    default<U> comparator<t>thencomparing (Function<?SuperT?extendsU>Keyextractor, Comparator<?SuperU>keycomparator) {        returnthencomparing (Comparing (Keyextractor, keycomparator)); }    default<uextendscomparable<?SuperU>> comparator<t>thencomparing (Function<?SuperT?extendsU>keyextractor) {        returnthencomparing (Comparing (keyextractor)); }    defaultComparator<t> thencomparingint (tointfunction<?SuperT>keyextractor) {        returnthencomparing (Comparingint (keyextractor)); }    defaultComparator<t> Thencomparinglong (tolongfunction<?SuperT>keyextractor) {        returnthencomparing (Comparinglong (keyextractor)); }    defaultComparator<t> thencomparingdouble (todoublefunction<?SuperT>keyextractor) {        returnthencomparing (comparingdouble (keyextractor)); }     Public Static<textendscomparable<?SuperT>> comparator<t>Reverseorder () {returnCollections.reverseorder (); } @SuppressWarnings ("Unchecked")     Public Static<textendscomparable<?SuperT>> comparator<t>Naturalorder () {return(comparator<t>) Comparators.NaturalOrderComparator.INSTANCE; }     Public Static<T> comparator<t> Nullsfirst (comparator<?SuperT>comparator) {        return NewComparators.nullcomparator<> (true, comparator); }     Public Static<T> comparator<t> nullslast (comparator<?SuperT>comparator) {        return NewComparators.nullcomparator<> (false, comparator); }     Public Static<t, u> comparator<t>Comparing (Function<?SuperT?extendsU>Keyextractor, Comparator<?SuperU>keycomparator)        {objects.requirenonnull (keyextractor);        Objects.requirenonnull (Keycomparator); return(Comparator<t> &Serializable) (c1, C2)-Keycomparator.compare (Keyextractor.apply (C1), keyextractor.apply (C2)); }     Public Static<t, Uextendscomparable<?SuperU>> comparator<t>Comparing (Function<?SuperT?extendsU>keyextractor)        {objects.requirenonnull (keyextractor); return(Comparator<t> &Serializable) (c1, C2)-keyextractor.apply (C1). CompareTo (keyextractor.apply (C2)); }     Public Static<T> comparator<t> comparingint (tointfunction<?SuperT>keyextractor)        {objects.requirenonnull (keyextractor); return(Comparator<t> &Serializable) (c1, C2)-Integer.compare (Keyextractor.applyasint (C1), Keyextractor.applyasint (C2)); }     Public Static<T> comparator<t> Comparinglong (tolongfunction<?SuperT>keyextractor)        {objects.requirenonnull (keyextractor); return(Comparator<t> &Serializable) (c1, C2)-Long.compare (Keyextractor.applyaslong (C1), Keyextractor.applyaslong (C2)); }     Public Static<T> comparator<t> comparingdouble (todoublefunction<?SuperT>keyextractor)        {objects.requirenonnull (keyextractor); return(Comparator<t> &Serializable) (c1, C2)-Double.compare (Keyextractor.applyasdouble (C1), keyextractor.applyasdouble (C2)); }}

The main differences between comparable and comparator are:

  (1). Both Comparator and comparable are internal comparator interfaces in Java and are used to implement sorting of a custom class

(2). The difference is that the implementation of the comparable interface is defined inside the class, and the comparison code needs to be embedded within the class's internal structure

(3). Comparator implementation of the outside of the class, the implementation of the first comparator, do not need to change the original class structure, belongs to the non-intrusive.

For example, implement the comparable interface:

    classScoreImplementsComparable<score>{         Public intscore;  Public intTime ;  Public intGetscore () {returnscore; }             Public voidSetScore (intscore) {           This. score =score; }             Public intGetTime () {returnTime ; }             Public voidSetTime (intTime ) {           This. Time =Time ; } @Override Public intCompareTo (Score o) {if( This. Time>o.time)return1; Else if( This. Time==o.time)return0; Else return-1; }                 PublicScore (intScore,intTime ) {              Super();  This. score =score;  This. Time =Time ; }      }   

Examples of implementing comparator interfaces:

    class Implements Comparator<score>{                @Override          publicint  Compare (score O1, score O2) {               if return 1;               Else if return 0;               Else return -1;          }         }  

Then call Scorecomparator:

New Scorecomparator ());

Reference: http://blog.csdn.net/hll174/article/details/50996199

The difference between comparator and comparable in Java

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.