The difference between the comparable interface and the comparator interface in Java

Source: Internet
Author: User
Tags comparable ming

I. The difference between comparable and comparator

1, comparable and comparator are used to implement the collection of elements in the comparison, sorting.

2. Comparable is the sort of method implementation defined within the class, located under Java.lang.

3. Comparator is the sort implemented outside the class, located under Java.util.

4, the realization comparable interface needs to overwrite the CompareTo method, realizes comparator interface needs to overwrite compare method.

5. The comparable interface embeds the comparison code in its own code of the class that needs to be compared, while the comparator interface implements comparisons in a separate class.

Two. In-depth understanding

First comparable this interface is used on the class of elements you need to sort.

While Comparator is not used on the element class you need to sort on, it needs to implement a subclass object that passes the subclass object into a sorted collection (TreeSet).

You have to modify the source code when you want to use the comparable interface, because he is built on the class of elements that need to be sorted.

What if you want to sort the string class in your own order? (for example, don't contradicting)

First you cannot modify the source code, the second string class is the final class cannot inherit.

At this point you can use the Comparator interface to sort outside the class

Three. Example

1. Implement comparable interface for element class node

 PackageCom.cjm.lambda;ImportJava.util.Set;ImportJava.util.TreeSet;/** *  * @authorXiao Ming **/ Public classSetsortlambda { Public Static voidMain (string[] args) {Set<Node> set =NewTreeset<>(); Set.add (NewNode ("Zs", 10)); Set.add (NewNode ("Zs1", 110)); Set.add (NewNode ("Zs1", 10)); Set.add (NewNode ("Zszx", 100)); Set.add (NewNode ("Zzxs", 10));    SYSTEM.OUT.PRINTLN (set); }}/** Elemental Native Implementation Comparator interface*/classNodeImplementsComparable<node> {    intnum;    String str;  PublicNode (String str,intnum) {         This. str=str;  This. num =num; } @Override Public intcompareTo (Node o) {if( This. str = =NULL) {            return-1; } Else {            if(O.str = =NULL) {                return1; } Else {                if( This. Str.length () <o.str.length ()) {                    return-1; } Else {                    if( This. Str.length () >o.str.length ()) {                        return1; } Else {                        if( This. Num <o.num) {return-1; } Else {                            if( This. num >o.num) {return1; } Else {                                return0; }                        }                    }                }            }        }    }    /*(non-javadoc) * @see java.lang.object#tostring ()*/@Override PublicString toString () {returnstr+num; }}

2. Use the comparator interface to implement an object with an comparator interface (in the form of an internal class)

 PackageCom.cjm.lambda;ImportJava.util.Comparator;ImportJava.util.Set;ImportJava.util.TreeSet;/*** Compararator Interface Implementation Sort * *@authorXiao Ming **/ Public classText { Public Static voidMain (string[] args) {Set<Node> set =NewTreeset<> (NewComparator<node>() {@Override Public intCompare (node Node1, node Node2) {if(Node1.str.length () <node2.str.length ()) {                    return1; } Else {                    if(Node1.str.length () >node2.str.length ()) {                        return-1; } Else {                        if(Node1.num <node2.num) {return1; } Else {                            if(Node1.num >node2.num) {return-1; } Else {                                return0;        }                        }                    }                }            }        }); Set.add (NewNode ("Zs", 10)); Set.add (NewNode ("Zs1", 110)); Set.add (NewNode ("Zs1", 10)); Set.add (NewNode ("Zszx", 100)); Set.add (NewNode ("Zzxs", 10));    SYSTEM.OUT.PRINTLN (set); }}

The difference between the comparable interface and the comparator interface 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.