Comparable and comparator interface difference analysis in Java

Source: Internet
Author: User
Tags comparable static class

Comparable and comparator interface difference analysis in Java

Source: Code Farming Network | Time: 2015-03-16-10:25:20 | Hits:8902

[Introduction] This article is to be detailed analysis of Java comparable and comparator interface differences, both have a comparative function, then what is the difference, interested Java developers continue to look at it. Comparable introduction comparable is a sort interface. If a class implements the Comparab

This article is to be detailed analysis of Java comparable and comparator interface differences, both have a comparative function, then what is the difference, interested Java developers continue to look at it.

Comparable introduction

Comparable is the sort interface.

If a class implements the comparable interface, it means "this class supports sorting." The class that implements the comparable interface supports sorting, assuming that there is now "a list (or array) of objects of the class implementing the comparable interface," then the list (or array) can be passed collections.sort (or Arrays.sort) to sort.

In addition, the "object of the class that implements the comparable interface" can be used as a key in an ordered map (such as treemap) or an element in an ordered collection (TreeSet), without specifying a comparer.

Comparable definition

The comparable interface only includes a function, which is defined as follows:

Package Java.lang;import java.util.*;p ublic interface comparable<t> {public    int compareTo (T o);}

Description

Suppose we "compare the size of x and Y" by X.compareto (y). If "negative" is returned, it means "x is smaller than Y"; return "0", meaning "x equals Y"; return "positive number", meaning "x is greater than Y".

Comparator Introduction

The Comparator is the comparator interface.

If we need to control the order of a class, and the class itself does not support ordering (that is, it does not implement the comparable interface), then we can create a "comparer for this class" to sort by. This "comparator" only needs to implement the comparator interface.

That is, we can create a new comparer by implementing the comparator class, and then sort the classes through the comparer.

Comparator definition

The Comparator interface consists of only two functions, which are defined as follows:

Package Java.util;public interface Comparator<t> {    int compare (t O1, T O2);    Boolean equals (Object obj);}

Description

(01) If a class is to implement the comparator interface: it must implement the CompareTo (t O1, T O2) function, but it can not implement the Equals (Object obj) function.

Why can I not implement the Equals (Object obj) function? Because of any class, the default is that you have implemented the Equals (Object obj). All classes in Java inherit from Java.lang.Object and implement the Equals (Object obj) function in Object.java, so all other classes are equivalent to implementing the function.

() int compare (t O1, T O2) is "Comparing the size of O1 and O2". Returns "negative number", meaning "O1 is smaller than O2"; returning "0" means "O1 equals O2"; returning "positive number" means "O1 is greater than O2".

Comparison of Comparator and comparable

Comparable is a sort interface, and if a class implements the comparable interface, it means "this class supports sorting."

And comparator is a comparator; if we need to control the order of a class, we can create a "comparer for that class" to sort by.

It is easy to see that comparable is equivalent to an "internal comparator", while comparator is equivalent to an "external comparator".

We use a test program to illustrate the two interfaces. The source code is as follows:

Import Java.util.*;import java.lang.comparable;/** * @desc The comparison program for "Comparator" and "comparable". * "Comparable" * It is a sort interface and contains only one function CompareTo (). * A class implements the comparable interface, meaning "the class itself supports sorting", which can be sorted directly by Arrays.sort () or Collections.sort (). * (Comparator) * It is a comparator interface that includes two functions: compare () and Equals (). * A class implements the comparator interface, then it is a "comparator". Other classes can be sorted according to the comparator. * * Summary: Comparable is an internal comparator, while comparator is an external comparator. * A class itself implements the comparable comparator, which means that it supports sequencing itself, and if it does not implement comparable itself, it can be sorted by an external comparator comparator.         */public class comparecomparatorandcomparabletest{public static void Main (string[] args) {//new ArrayList (dynamic array)        arraylist<person> list = new arraylist<person> ();        Add objects to ArrayList in List.add (New person ("CCC", 20));        List.add (New person ("AAA", 30));        List.add (The New person ("BBB", 10));        List.add (New person ("ddd", 40));        Prints the original sequence of the list System.out.printf ("Original Sort, list:%s\n", list); Sort list//This will be based on the "person implementation of the Comparable<sTring> interface "is sorted according to" name "Collections.sort (list);        System.out.printf ("Name Sort, list:%s\n", list); With the comparator (ascagecomparator), the list is sorted//Ascagecomparator in ascending order according to "Age" collections.sort (list, new ASC        Agecomparator ());        System.out.printf ("ASC (age) Sort, list:%s\n", list); With the comparator (descagecomparator), the list is sorted//Descagecomparator in descending order according to "Age" collections.sort (list, new D        Escagecomparator ());        System.out.printf ("Desc (age) Sort, list:%s\n", list);    Determine if two person is equal testequals ();     }/** * @desc test if two person comparisons are equal.     * Because person implements the Equals () function: If both age and name are equal, the two person is considered equal.     * So, here the P1 and P2 are equal. * TODO: If you remove the Equals () function in person, then P1 is not equal to P2 */private static void Testequals () {person P1 = new Person ("        Eee ", 100);        person P2 = new Person ("Eee", 100);        if (P1.equals (p2)) {System.out.printf ("%s EQUAL%s\n", p1, p2); } else {            System.out.printf ("%s not EQUAL%s\n", p1, p2);     }}/** * @desc person class.        * Person implements the comparable interface, which means that the person itself supports sort */private static class person implements comparable<person>{        int age;        String name;            Public person (String name, Int. age) {this.name = name;        This.age = age;        } public String GetName () {return name;        } public int Getage () {return age;        } public String toString () {return name + "-" +age;            /** * Compares two person equals: if their name and age are equal, they are considered equal */Boolean equals (person person) {            if (this.age = = Person.age && this.name = = Person.name) return true;        return false;         }/** * @desc implement the "Comparable<string>" interface, which overrides the Compareto<t t> function. * Here is a comparison by "person's name" */@Override public int CompaReTo (person person) {return Name.compareto (person.name);        return this.name-person.name; }}/** * @desc ascagecomparator Comparator * It is the "ascending comparator for the age of person" */private static Class Ascagecompar            Ator implements comparator<person> {@Override public int compare (person P1, person p2) {        Return P1.getage ()-p2.getage (); }}/** * @desc descagecomparator Comparator * It is the "ascending comparator for the age of person" */private static Class Descagecomp            Arator implements comparator<person> {@Override public int compare (person P1, person p2) {        Return P2.getage ()-p1.getage (); }    }}

This procedure is described below.

A) the person class definition. As follows:

private static class person implements comparable<person>{    int age;    String name;        ...    /**      * @desc Implement the "Comparable<string>" interface, which overrides the Compareto<t t> function.     *  Here is a comparison by "person's name" *    /@Override public    int compareTo (person person) {        return Name.compareto (person.name);        return this.name-person.name;    }   }

Description

The person class represents a human, with two attributes in the Persong class: Age and Name.
The person class implements the comparable interface, so it can be sorted.

b) in main (), we create a list of person's array (list). As follows:

New ArrayList (dynamic array) arraylist<person> list = new arraylist<person> ();//Add object to ArrayList List.add (new Person ("CCC"), List.add ("AAA"), List.add ("The New Person" ("BBB"), List.add ("ddd", 40));

c) Next, we print out all the elements of the list. As follows:

Prints the original sequence of the list System.out.printf ("Original Sort, list:%s\n", list);

D) Then we sort the list by Collections's sort () function.

Because person implements the comparable interface, sorting by sort () is sorted according to the sort that the person supports, that is, the rules defined by compareTo (person person). As follows:

Sort list//This will be sorted according to "person implemented Comparable<string> interface", which will be sorted according to "name" Collections.sort (list); System.out.printf ("Name Sort, list:%s\n", list);

e) Compare comparable and comparator

We defined two comparators, Ascagecomparator and Descagecomparator, to sort the ascending and descending order of the person individually.

E.1) Ascagecomparator Comparator

It is the ascending order of the person by age. The code is as follows:

/** * @desc Ascagecomparator Comparator *       It is "the ascending comparator for the age of person" */private static class Ascagecomparator implements Comparator <Person> {    @Override public    int compare (person P1, person p2) {        return p1.getage ()-P2.getage ();}    }

E.2) Descagecomparator Comparator

It is to sort the person in descending order of age. The code is as follows:

/** * @desc Descagecomparator Comparator *       It is the "ascending comparator for the age of person" */private static class Descagecomparator implements comparator<person> {    @Override public    int compare (person P1, person p2) {        return p2.getage ()- P1.getage ();    }}

f) Operating results

Run the program with the output as follows:

Original  Sort, list:[ccc-20, AAA-30, bbb-10, ddd-40]name      Sort, list:[aaa-30, bbb-10, ccc-20, ddd-4 0]ASC (age)  sort, list:[bbb-10, ccc-20, AAA-30, Ddd-40]desc (age) Sort, list:[ddd-40, AAA-30, ccc-20, BBB -10]eee-100 EQUAL eee-100


Excerpted from http://www.php100.com/html/it/biancheng/2015/0316/8790.html

Comparable and comparator interface difference analysis 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.