Article From:https://www.cnblogs.com/hithongming/p/9218491.html
Back to the top

One, a brief introduction to Comparable

  ComparableIt is the sort interface. If a class implements the Comparable interface, it means that the class supports sorting. A list or array of objects that implements Comparable interface classes can be automatically arranged through Collections.sort or Arrays.sort.Order.

  In addition, objects that implement this interface can be used as keys in ordered mapping or collections in ordered sets without specifying comparators. The interface is defined as follows:

package java.lang;
import java.util.*;
public interface Comparable<T> 
{     public int compareTo(T o); }

  TRepresents the type of objects that can be compared with this object.

  This interface has only one method, compare, to compare the order of the object to the specified object, and if the object is less than, equal to, or greater than the specified object, it returns a negative integer, a zero or a positive integer respectively.

  Now let’s suppose a Person class. The code is as follows:

public class Person
{
    String name;
    int age;
    public Person(String name, int age)
    {
        super();
        this.name = name;
        this.age = age;
    }
    public String getName()
    {
        return name;
    }
  public int getAge() { return age; } }

  Now there are two objects in the Person class. How do we compare the size of the two? We can make Comparable interface by Person:

public class Person implements Comparable<Person>
{
    String name;
    int age;
    public Person(String name, int age)
    {
        super();
        this.name = name;
        this.age = age;
    }
    public String getName()
    {
        return name;
    }
    public int getAge()
    {
        return age;
    }
    @Override
    public int compareTo(Person p)
    {
        return this.age-p.getAge();
    }
    public static void main(String[] args)
    {
        Person[] people=new Person[]{new Person("xujian", 20),new Person("xiewei", 10)};
        System.out.println(""Before sorting";For (Person person: people){System.out.print (person.getName () +":" +person.getAge ());}Arrays.sort (people);System.out.println ("after \n sort");For (Person person: people){System.out.print (person.getName () + ":" +persoN.getAge ());}}}

  The results of the program execution are as follows:

  

Back to the top

Two, a brief introduction to Comparator

  ComparatorIs the comparison interface, if we need to control the order of a class, and the class itself does not support the sort (that is, there is no implementation of the Comparable interface), then we can set up a “class comparator” to sort it, and this “comparator” only needs to implement the Comparator interfaceYou can. That is to say, we can create a comparator by implementing Comparator, and then sort the class through this comparator. The interface is defined as follows:

package java.util;
public interface Comparator<T>
 {
    int compare(T o1, T o2);
    boolean equals(Object obj);
 }

Note: 1, if a class implements Comparator interface, it must implement compare (T O1, T O2) function, but equals (Object obj) function can not be implemented.

   2、int compare(T o1, T o2) It’s “the size of O1 and O2”. Returning “negative number” means “O1 is smaller than O2”; returning to “zero” means “O1 equals O2”; returning “positive number” means “O1 is greater than O2”.

  Now, if the Person class above does not implement the Comparable interface, how does it compare? We can create a new class to implement the Comparator interface, thus constructing a comparator.

public class PersonCompartor implements Comparator<Person>
{
    @Override
    public int compare(Person o1, Person o2)
    {
        return o1.getAge()-o2.getAge();
    }
}

  Now we can use this comparator to sort it.

public class Person
{
    String name;
    int age;
    public Person(String name, int age)
    {
        super();
        this.name = name;
        this.age = age;
    }
    public String getName()
    {
        return name;
    }
    public int getAge()
    {
        return age;
    }
    public static void main(String[] args)
    {
        Person[] people=new Person[]{new Person("xujian", 20),new Person("xiewei", 10)};
        System.out.println(""Before sorting";For (Person person: people){System.out.print (person.getName () +":" +person.getAge ());}Arrays.sort (people, new PersonCompartor ());System.ouT.println ("after \n sort");For (Person person: people){System.out.print (PersOn.getName () + ":" +person.getAge ());}}}

  The results of the program run are as follows:

  

Back to the top

Comparison of three, Comparable and Comparator

  ComparableIt is a sort interface. If a class implements Comparable interface, it means that the class supports sorting. Comparator is a comparator. If we need to control the order of a class, we can set up a comparator of this kind to sort it.

  ComparableIt is equivalent to the “internal comparator”, while Comparator is equivalent to the “external comparator”.

  The two methods have their own advantages and disadvantages, with Comparable simple, as long as the object of the implementation of the Comparable interface becomes an object that can be compared, but the source code needs to be modified. The advantage of using Comparator is that you do not need to modify the source code, but ratherIn addition, a comparator is implemented. When a custom object needs to be compared, the comparator and the object can be passed in the past with the size, and in the Comparator, the user can implement the complex and general logic itself, so that it can match some simpler pairs.Like that, you can save a lot of repetitive work.

Leave a Reply

Your email address will not be published. Required fields are marked *