"Reprint" Java comparable and comparator comparison

Source: Internet
Author: User
Tags class definition comparable

"This article goes from" http://www.cnblogs.com/skywang12345/p/3324788.html

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:

  1 Import java.util.*;  2 Import java.lang.Comparable;  3 4/** 5 * @desc The comparison procedure for "Comparator" and "comparable".  6 * (comparable) 7 * It is a sort interface and contains only one function CompareTo ().  8 * A class implements the comparable interface, meaning "the class itself supports sorting", which can be sorted directly by Arrays.sort () or Collections.sort (). 9 * () "Comparator" 10 * It is a comparator interface, including two functions: compare () and Equals (). 11 * A class implements the comparator interface, then it is a "comparator". Other classes can be sorted according to the comparator. 12 * 13 * In summary: Comparable is an internal comparator, while comparator is an external comparator. 14 * A class itself implements the comparable comparator, which means that it natively supports sequencing, 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) {19 New ArrayList (dynamic array) arraylist<person> list = new arraylist<person> (); 21//Add object to ArrayList in List.add (New person ("CCC", 20)); List.add (New person ("AAA", 30)); List.add ("BBB", 10); List.add (New person ("ddd", 40)); 26 27//Print the original sequence of the list to System.out.printf ("Original Sort, list:%s\n", list); 29 30//Sort list 31//This will be sorted according to "person implemented Comparable<string> interface", which will be sorted according to "name". Collect Ions.sort (list); System.out.printf ("Name Sort, list:%s\n", list); 34 35//through "Comparator (ascagecomparator)", the list is sorted by the order of the Ascagecomparator: according to "age" in ascending order of the PNS Collect Ions.sort (list, new Ascagecomparator ()); System.out.printf ("ASC (age) Sort, list:%s\n", list); 39 40//Through the "Comparator (Descagecomparator)", the list is sorted by the sort by: "Age" in descending order of the Colle Ctions.sort (list, new Descagecomparator ()); System.out.printf ("Desc (age) Sort, list:%s\n", list); 44 45//Determine whether two person is equal to testequals (); /** * @desc Test Two person comparisons for equality. 51 * Because person implements the Equals () function: If both age and name are equal, the two person is considered equal. 52 * So, the P1 and P2 here are equal. * * * TODO: If you remove the Equals () function in person, then P1 is not equal to P2 55 */56     private static void Testequals () {p1 = new person ("eee", +), p2 = new Person (" Eee ", 100);             if (P1.equals (p2)) {System.out.printf ("%s EQUAL%s\n", p1, p2); System.out.printf ("%s not EQUAL%s\n", p1, p2); The/** * @desc Person class. The comparable interface is implemented by the person, which means that the person itself supports the sort. * */private static class person implements comparable             <person>{(string name, int age) {75), string name; THIS.name = name; This.age = age; GetName () () () () {n-return name; Bayi}  EtAge () {"Return Age", "()" * * * * * * * * The public String toString () {return name + " -"+age; 89} 90 91/** 92 * Compare two person equality: if their name and age are equal, they are considered equal to the * * * 94 Boolean equals (person person) {This.age = = person.age && th Is.name = = person.name)-return true; return false; 98}/**101 * @desc implementation of the "comparable<string>" interface, that is, overriding the Compareto<t t> function. 102 * Here is a comparison of 103 */104 @Override105 public int compareTo with "person's name" { 106 return Name.compareto (person.name); 107//return this.name-person.name;108}109} 111/**112 * @desc Ascagecomparator Comparator 113 * It is "the ascending comparator of the age of person" */115 private static Class Ascagecomparator implements comparator<person> {117 @Override 118 public int Compa  Re (person P1, person p2) {119 return P1.getage ()-p2.getage (); 120}121}122 123/**124 *    @desc Descagecomparator Comparator 125 * It is "the ascending comparator of the age of the person" 126  */127 private Static Class Descagecomparator implements Comparator<person> {129 @Override     Compare public int * (person P1, person p2) {131 return p2.getage ()-p1.getage (); 132}133 }134 135}

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 (); c13/>}}

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

"Reprint" Java comparable and comparator comparison

Related Article

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.