Comparison of comparable and comparator in Java

Source: Internet
Author: User
Tags arrays comparable comparison implement printf sort static class


In this article, we introduce the comparable and comparator two interfaces, and their differences, and then, by example, explain how they are used.



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 for the class that implements the comparable interface, the list (or array) can be passed through Collections.sort (or Arrays.sort) to sort.



In addition, the object of the class implementing the comparable interface can be used as a key in an ordered map (such as TreeMap) or as 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.*;



Public interface Comparable<t> {
public int compareTo (T o);
}



Description
Suppose we use X.compareto (y) to "compare the size of x and Y". Returning a "negative number" means "x is smaller than Y"; returning "0" means "x equals Y"; returning "positive" means "X is greater than Y".



Comparator Introduction



Comparator is the comparator interface.



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



That is, we can create a new comparer by implementing the comparator class, and then sort the class by 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 implements the comparator interface: it must implement the CompareTo (t O1, T O2) function, but it may not implement the Equals (Object obj) function.



Why not implement the Equals (Object obj) function? Because any class, the default is already implemented 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.



The int compare (t O1, T O2) is the size of the comparison O1 and O2. Returning "negative numbers" means "O1 is smaller than O2"; returning "0" means "O1 equals O2"; returning "positive" 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.



We are not hard to find: comparable is equivalent to "internal comparator", and comparator is equivalent to "external comparator".



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


import java.util. *;
import java.lang.Comparable;
     
/ **
 * @desc "Comparator" and "Comparable" comparison program.
 * (01) "Comparable"
 * It is a sorting interface and contains only a function compareTo ().
 * A class implements the Comparable interface, which means "the class itself supports sorting", and it can be sorted directly by Arrays.sort () or Collections.sort ().
 * (02) "Comparator"
 * It is a comparator interface and includes two functions: compare () and equals ().
 * A class implements the Comparator interface, then it is a "comparator". Other classes can be sorted by this comparator.
 *
 * To sum up: Comparable is an internal comparator, and Comparator is an external comparator.
 * A class itself implements the Comparable comparator, which means that it supports sorting itself; if it does not implement Comparable itself, it can also be sorted by the external comparator Comparator.
 * /
public class CompareComparatorAndComparableTest {
     
    public static void main (String [] args) {
        // create a new ArrayList (dynamic array)
        ArrayList <Person> list = new ArrayList <Person> ();
        // Add objects to ArrayList
        list.add (new Person ("ccc", 20));
        list.add (new Person ("AAA", 30));
        list.add (new Person ("bbb", 10));
        list.add (new Person ("ddd", 40));
     
        // print the original sequence of list
        System.out.printf ("Original sort, list:% sn", list);
     
        // Sort the list
        // Sort here according to "Comparable <String> interface implemented by Person", that is, sort according to "name"
        Collections.sort (list);
        System.out.printf ("Name sort, list:% sn", list);
     
        // Sort the list by "AscAgeComparator"
        // AscAgeComparator is sorted by: ascending order of "age"
        Collections.sort (list, new AscAgeComparator ());
        System.out.printf ("Asc (age) sort, list:% sn", list);
     
        // Sort the list by "Comparator (DescAgeComparator)"
        // DescAgeComparator is sorted by: descending order of "age"
        Collections.sort (list, new DescAgeComparator ());
        System.out.printf ("Desc (age) sort, list:% sn", list);
     
        // determine if two persons are equal
        testEquals ();
    }
     
    / **
     * @desc tests if two Persons are equal.
     * Because Person implements the equals () function: if the age and name of two persons are equal, the two persons are considered equal.
     * So, p1 and p2 are equal here.
     *
     * TODO: If the equals () function in Person is removed, 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% sn", p1, p2);
        } else {
            System.out.printf ("% s NOT EQUAL% sn", p1, p2);
        }
    }
     
    / **
     * @desc Person class.
     * Person implements the Comparable interface, which means that Person itself supports sorting
     * /
    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;
        }
     
        / **
         * Compare whether two Persons are equal: 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 implements the interface of "Comparable <String>", which is to override 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 "Ascending Comparator of Person's Age"
     * /
    private static class AscAgeComparator implements Comparator <Person> {
             
        @Override
        public int compare (Person p1, Person p2) {
            return p1.getAge ()-p2.getAge ();
        }
    }
     
    / **
     * @desc DescAgeComparator comparator
     * It is "Ascending Comparator of Person's Age"
     * /
    private static class DescAgeComparator implements Comparator <Person> {
             
        @Override
        public int compare (Person p1, Person p2) {
            return p2.getAge ()-p1.getAge ();
        }
    }
     
}


See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/Java/



The following is a description of the program.





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.