Compare the comparable sort interface in Java with the comparator comparator interface _java

Source: Internet
Author: User
Tags arrays class definition comparable static class

Comparable
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.
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".
The comparable interface is already generic, so the object that implements the comparable declares what type it can compare with. (Typically, this is the type of the object itself, but it can sometimes be a parent class.) )
Public interface Comparable {public boolean compareTo (T-Other);}
So the comparable interface contains a type parameter T, which is the type of object that the class that implements the comparable can compare to. This means that if you define a class that implements comparable, such as String, you must not only declare a class support comparison, but also declare what it can compare with (usually compared to itself):
public class String implements comparable {...}
Now consider the implementation of a two-dollar max () method. You want to accept two parameters of the same type, both of which are comparable and comparable with each other. Fortunately, this is fairly intuitive if you use generic methods and restricted type parameters:
public static > t max (t T1, T T2) {if (T1.compareto (T2) > 0) return t1; else return T2;}
In this example, you define a generic method that is generic on type T, and you constrain the type extension (implementation) comparable. All two parameters must be of type T, which means they are of the same type, support comparisons, and can be compared to each other. Easy!
Better yet, the compiler will use type inference to determine what the value of T means when calling Max (). So you don't have to specify T at all, and the following call works:

String s = max ("moo", "bark");

The compiler will calculate that the predetermined value for T is String, so it will compile and type check. However, if you attempt to call Max () with a parameter that does not implement the comparable class X, the compiler will not allow this.

Comparator
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.
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
1. 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.
2.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."

Comparator and comparable compare
comparable are sort interfaces, and if a class implements a comparable interface, it means "this class supports sorting."
and comparator are comparators; if we need to control the order of a class, we can create a "comparer for that class" to sort.
It is not hard to find that comparable is equivalent to an "internal comparator" and that the comparator corresponds to an "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 procedures.
 * (+) "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 ().
 * (s) "Comparator" * It is a comparator interface, consisting of 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<person> list = new arraylist<person> ();
    Add object 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);

    Prints the original sequence of the list System.out.printf ("Original Sort, list:%s\n", list); Sort the list//this will be sorted according to the "Comparable<string> Interface for person implementation", which will be based on the "NAMe "to sort collections.sort (list);

    System.out.printf ("Name Sort, list:%s\n", list); The list is sorted//Ascagecomparator by the comparer (Ascagecomparator), sorted by the ascending sort of "age" collections.sort (list, new ascagecom
    Parator ());

    System.out.printf ("ASC (age) Sort, list:%s\n", list); The list is sorted//Descagecomparator by the comparer (descagecomparator) by sorting the Collections.sort according to the descending order of age (list, new descage
    Comparator ());

    System.out.printf ("Desc (age) Sort, list:%s\n", list);
  Determine whether two person is equal testequals ();
   /** * @desc test whether 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, then P1 is not equal to P2/private static void Testequals () {person P1 = new person ("Eee", 1
    00);
    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 personClass. * Person implements the comparable interface, which means that the person itself supports sorting/private static class person implements comparable<person>{I
    NT 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 interface of "comparable<string>", that is, to override the Compareto<t t> function. * This is compared by "person's name" * * @Override public int compareTo (person person) {return Name.compareto
      . name);
    return this.name-person.name; }/** * @desc ascagecomparator comparer * 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 (); }/** * @desc descagecomparator comparer * It is "the ascending comparator for the age of person"/private static Class Descagecomparator I Mplements comparator<person> {@Override public int compare (person P1, person p2) {return p2.getage
    ()-p1.getage ();

 }
  }
}

The following is a description of the program.
1.Person class definition. As follows:

private static class person implements comparable<person>{
  int age;
  String name;

    ...

  /** 
   * @desc Implement the "Comparable<string>" interface, that is, rewrite the compareto<t t> function.
   * This is compared by "person's name" * *
  @Override public
  int CompareTo
    Name.compareto (person.name);
    Return This.name-person.name
  }  
} 

Description
(1) The person class represents a human, and there are two attributes in the Persong class: Age and Name "name".
(2) The person class implements the comparable interface, so it can be sorted.

2. In main (), we created the list of person's lists. As follows:

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

3. Then, 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);

4. 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:

Sort the list
//This will be 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);

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

6.AscAgeComparator Comparator
It is the ascending sort of 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 ();
  }
}

7.DescAgeComparator Comparator
It sorts the descending order of person by 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) { C20/>return p2.getage ()-p1.getage ();
  }
}

8. Run the results run the program, the output is as follows:

Original sort, list:[ccc-20, AAA-30, bbb-10, ddd-40]
Name   Sort, list:[aaa-30, bbb-10, ccc-20, DDD-
ASC (age) Sort, list:[bbb-10, ccc-20, AAA-30, ddd-40]
Desc (age) Sort, list:[ddd-40, AAA-30, ccc-2 0, bbb-10]
eee-100 EQUAL eee-100

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.