1. Introduction

Is simple to java.util.Com parator illustrates, today we are going to see another parable java.lang.Com and it is very similar to interfaces.

2. Comparable

The Comparable interface also has only one abstract method, int compareTo(T o), whose rules are similar to the Comparator’s int compare(T o1, T O2). Although it can also be considered a functional interface, it is not marked as such in Java 8. Note that the designers do not want developers to use it as a functional interface. To do otherwise is to deviate from the design intent, as in the following type a string to return the length of the string.

// An operation that is syntactic but does not conform to the design intent
Comparable<String> comparable = String::length;
Copy the code

Comparable is typically intended as a feature of an object to indicate that instances of that object are compared to each other. Movies, for example, have the feature of comparing by year.

class Movie implements Comparable<Movie> { 
    private double rating; 
    private String name; 
    private int year; 
  
    // Used to sort movies by year 
    public int compareTo(Movie m){ 
        return this.year - m.year; }}Copy the code

Comparable is usually used for natural ordering, where the element itself is Comparable.

3.Comparator vs Comparable

Comparator is similar to Comparable, but there are a few differences between Comparator and Comparable:

  • Different perspectives,ComparableIt is usually a comparison property that comes with the objectComparatorIt is usually compared as a “third party”.
  • usuallyComparableNeeds to be implemented by the object to be used as a feature, whileComparatorMore of a strategy.
  • A is located in thejava.langWrap it up, one injava.utilNext, this also proves the first one from the side.

4. To summarize

In summary, use Comparable if an object needs to be sorted based on natural order (which is itself Comparable), and use Comparator if you need to sort different properties by business.

Follow our public id: Felordcn for more information

Personal blog: https://felord.cn