Detailed explanation and comparison of Comparable and Comparator in java

  • 2020-06-19 10:26:34
  • OfStack

Details of Comparable and Comparator in java

Looking at the source code of TreeMap today, I found that the key must be the interface of Comparable or Comparator. For example, the put method in TreeMap handles the interface of Comparable and Comparator respectively. So the question is, what is the difference between Comparable and Comparator interfaces, and why are there two similar interfaces in Java?

The & # 8195; The & # 8195; Both Comparable and Comparator interfaces are used to compare sizes. Let's first look at the definition of Comparable:


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

The & # 8195; The & # 8195; Comparator is defined as follows:


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

The & # 8195; The & # 8195; Comparable sorts the objects of each class that implements it as a whole. This interface requires the class itself to implement. It doesn't matter. Here's an example. If a class implements the Comparable interface, the List list (or array) of objects of the class that implements the Comparable interface can be sorted by Collections.sort (or Arrays.sort). In addition, objects of classes that implement the Comparable interface can be used as keys in "ordered maps (such as TreeMap)" or elements in "ordered collections (TreeSet)" without specifying comparators.

The & # 8195; The & # 8195; Example (Class Person1 implements the Comparable interface)


package collections;

public class Person1 implements Comparable<Person1>
{
  private int age;
  private String name;

  public Person1(String name, int age)
  {
    this.name = name;
    this.age = age;
  }
  @Override
  public int compareTo(Person1 o)
  {
    return this.age-o.age;
  }
  @Override 
  public String toString()
  {
    return name+":"+age;
  }
}

The & # 8195; The & # 8195; You can see that Person1 implements the compareTo method in the Comparable interface. To implement the Comparable interface, you must modify your own class, that is, implement the corresponding methods in the interface in your own class.

The & # 8195; The & # 8195; Test code:


 Person1 person1 = new Person1("zzh",18);
    Person1 person2 = new Person1("jj",17);
    Person1 person3 = new Person1("qq",19);

    List<Person1> list = new ArrayList<>();
    list.add(person1);
    list.add(person2);
    list.add(person3);

    System.out.println(list);
    Collections.sort(list);
    System.out.println(list);

The & # 8195; The & # 8195; Output results:


[zzh:18, jj:17, qq:19]
[jj:17, zzh:18, qq:19]

The & # 8195; The & # 8195; If our class cannot be modified, such as String, we need to sort it again. Of course, Comparable already implements the Comparable interface in String, so it's not obvious to just use String as an example. The class itself cannot be modified so the interface Comparator (policy mode) is used.


public final class Person2
{
  private int age;
  private String name;

  public Person2(String name, int age)
  {
    this.name = name;
    this.age = age;
  }

  @Override 
  public String toString()
  {
    return name+":"+age;
  }

  //getter and setter Methods omit ....
}

The & # 8195; The & # 8195; For example, the class Person2, which is fixed and cannot be modified to its own class, is also modified final, and you can't inherit from implements Comparable, so what do you do? Use the interface of Comparator outside of the class. The following test code:


 Person2 p1 = new Person2("zzh",18);
    Person2 p2 = new Person2("jj",17);
    Person2 p3 = new Person2("qq",19);
    List<Person2> list2 = new ArrayList<Person2>();
    list2.add(p1);
    list2.add(p2);
    list2.add(p3);
    System.out.println(list2);
    Collections.sort(list2,new Comparator<Person2>(){

      @Override
      public int compare(Person2 o1, Person2 o2)
      {
        if(o1 == null || o2 == null)
          return 0;
        return o1.getAge()-o2.getAge();
      }

    });
    System.out.println(list2);

The & # 8195; The & # 8195; Output results:


[zzh:18, jj:17, qq:19]
[jj:17, zzh:18, qq:19] 

The & # 8195; The & # 8195; Here you go (public static < T > void sort(List < T > list, Comparator < ? super T > c) adopted the internal class implementation method, compare method, class Person2 list sort.

The & # 8195; The & # 8195; For example, in the real case encountered by the blogger, String needs to be sorted, case insensitive, we know that the sort in String is dictionary sort, for example: A a D after the sort is A D a, which is obviously wrong, so what should we do? Ditto (list in the following code is the List set of 1 String) :


 Collections.sort(list, new Comparator<String>()
    {
      @Override
      public int compare(String o1, String o2)
      {
        if(o1 == null || o2 == null)
          return 0;
        return o1.toUpperCase().compareTo(o2.toUpperCase());
      }
    });

The & # 8195; The & # 8195; In this way, it is possible to sort String's collection without distinguishing its size

The & # 8195; The & # 8195; Careful students may have questions, when two methods are defined in Comparator interface, why is it that only one method is implemented when inheriting the Java interface?

The & # 8195; The & # 8195; In fact, we know that when a class does not explicitly inherit the parent class, there will be a default superclass, namely java. lang. Object, in Object class with one method for equals method, namely so there is no mandatory implementation Comparator interface classes to achieve equals method, direct call the superclass can, although you explicitly implemented equals () method will be a better choice ~

The & # 8195; The & # 8195; In Effective Java 1, the author of Joshua Bloch recommends that you consider implementing the Comparable interface as much as possible when writing custom classes. Once the Comparable interface is implemented, it can work with many generic algorithms and collections of implementations that depend on the modified interface. You can achieve very powerful functions with very little effort.

The & # 8195; The & # 8195; In fact, all the value classes in the Java platform class library implement the Comparable interface. If you're writing a value class that has obvious intrinsic sorting relationships, such as alphabetical, numeric, or chronological, you should definitely consider implementing this interface.

The & # 8195; The & # 8195; The compareTo method not only allows simple equality comparisons, but also performs order comparisons in word order. In addition, it has similar characteristics to Object's equals method, which is also a generic type. Class implements the Comparable interface, indicating that its instance has inherent sorting relationships. Sorting an array of objects implementing the Comparable interface is as simple as that: ES155en.sort (a);

The & # 8195; The & # 8195; Searching Comparable objects stored in collections, calculating limits, and automatic maintenance are equally simple. For example, the following program implements the Comparable interface by relying on String, which removes duplicate arguments from the command line argument list and prints them out alphabetically:


public class WordList{
  public static void main(String args[]){
    Set<String> s = new TreeSet<String>();
    Collections.addAll(s,args);
    System.out.println(s);
  }
}

The & # 8195; The & # 8195; Comparable is the sort interface; If a class implements the Comparable interface, that means "the class supports sorting." Comparator is the comparator; If we want to control the order of a class, we can create a comparator of this class to sort it.

The & # 8195; The & # 8195; The former should be fixed and tied to a specific class, while the latter is flexible and can be used by classes that require comparison functionality. The former can be said to be "statically bound," while the latter can be "dynamically bound."

The & # 8195; The & # 8195; It is not hard to see that Comparable is equivalent to an "internal comparator", while Comparator is equivalent to an "external comparator".

Thank you for reading, I hope to help you, thank you for your support to this site!


Related articles: