Comparison between comparable and comparator in Java _java

Source: Internet
Author: User
Tags class definition comparable static class
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:


Copy Code code 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:


Copy Code code 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:


Copy Code code as follows:



Import java.util.*;


Import java.lang.Comparable;


/**


* @desc "Comparator" and "comparable" comparison procedures.


* (a) "comparable"


* It is a sort interface that contains only one function CompareTo ().


* A class implements the comparable interface, meaning that 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 "comparer". Other classes, which can be sorted according to the comparer.


*


* To sum up: comparable is an internal comparator, and comparator is an external comparator.


* A class itself implements the comparable comparer, meaning that it supports sorting itself, and if it does not implement comparable itself, it can also be sorted by an external comparer comparator.


*/


public class comparecomparatorandcomparabletest{


public static void Main (string[] args) {


New ArrayList (dynamic array)


arraylist&lt;person&gt; list = new arraylist&lt;person&gt; ();


adding 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 the list


System.out.printf ("Original Sort, list:%s\n", list);


Sort the list


This is sorted according to the "Comparable&lt;string&gt; Interface for person implementation", which is sorted according to "name"


Collections.sort (list);


System.out.printf ("Name Sort, list:%s\n", list);


Sort list By "comparer (Ascagecomparator)"


Ascagecomparator Sort by: sorted by ascending order of "age"


Collections.sort (list, new Ascagecomparator ());


System.out.printf ("ASC (age) Sort, list:%s\n", list);


Sort list By "comparer (Descagecomparator)"


Descagecomparator is sorted by descending order of "age"


Collections.sort (list, new Descagecomparator ());


System.out.printf ("Desc (age) Sort, list:%s\n", list);


Determine whether two person is equal


Testequals ();


}


/**


* @desc Test Two person comparisons are equal.


* Because person implements the Equals () function: If both the age and name are equal, the two is considered equal.


* So, the P1 and P2 are equal.


*


* TODO: If you remove the Equals () function in person, 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 sorting


*/


private static class person implements comparable&lt;person&gt;{


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 two person equality: if their name and age are equal, they are considered equal


*/


Boolean equals (person person) {


if (this.age = = Person.age &amp;&amp; this.name = = person.name)


return true;


return false;


}


/**


* @desc Implement "comparable&lt;string&gt;" interface, that is, rewrite the compareto&lt;t t&gt; function.


* This is compared 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 comparer for the age of person"


*/


private static class Ascagecomparator implements Comparator&lt;person&gt; {


@Override


public int compare (person P1, person p2) {


Return P1.getage ()-p2.getage ();


}


}


/**


* @desc Descagecomparator Comparator


* It is "the ascending comparer for the age of person"


*/


private static class Descagecomparator implements Comparator&lt;person&gt; {


@Override


public int compare (person P1, person p2) {


Return P2.getage ()-p1.getage ();


}


}


}





The following is a description of the program.


A) the person class definition. As follows:


Copy Code code as follows:

private static class person implements comparable<person>{
int age;
String name;
...
/**
* @desc Implement "comparable<string>" interface, that is, rewrite the compareto<t t> function.
* This is compared by "person's name".
*/
@Override
public int compareTo (person person) {
Return Name.compareto (Person.name);
return this.name-person.name;
}
}



Description


The People class represents a person, and there are two attributes in the Persong class: Age and Name "name".


The person class implements the comparable interface, so it can be sorted.


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


Copy Code code as follows:

New ArrayList (dynamic array)
arraylist<person> list = new arraylist<person> ();
adding 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);



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


Copy Code code as follows:

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



D Then, we sort the list by collections the sort () function.


Because person implements the comparable interface, sorting by sort () is sorted by the rules defined by the person that is supported by the person, i.e. compareTo. As follows:


Copy Code code as follows:

Sort the list
This is sorted according to the "Comparable<string> Interface for person implementation", which is sorted according to "name"
Collections.sort (list);
System.out.printf ("Name Sort, list:%s\n", list);



e) contrasting comparable and comparator


We have defined two comparators ascagecomparator and Descagecomparator to perform ascending and descending sorting on the person individually.


E.1) Ascagecomparator Comparator


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


Copy Code code as follows:

/**
* @desc Ascagecomparator Comparator
* It is "the ascending comparer 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 sorts the descending order of person by age. The code is as follows:


Copy Code code as follows:

/**
* @desc Descagecomparator Comparator
* It is "the ascending comparer 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) Run results


Run the program, the output is as follows:


Copy Code code as follows:

original  sort, list:[ccc-20, AAA-30, bbb-10, ddd-40]
Name&nb sp;     sort, list:[aaa-30, bbb-10, ccc-20, ddd-40]
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 -MB
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.