
1. preface
previous article easy, right java.util.Comparator
After explaining it, today let's look at another interface that is very similar to it java.lang.Comparable
。
2. Comparable
Comparable
An interface also has only one abstract method int compareTo(T o)
, its rules andComparator
theint compare(T o1, T o2)
similar. Although it can also be viewed as a functional interface, Java 8 It is not marked as a functional interface in. Explain that the designer does not want developers to use it as a functional interface. Otherwise, you deviate from the design intent, like typing a string below and returning the length of the string.
//Operations that conform to the syntax but do not conform to the design intent
Comparable<String> comparable = String::length;
under normal circumstancesComparable
Instances of an object that you want to express as a characteristic of the object are compared with each other. For example, movies 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;
}
}
Comparable is often used for natural sorting, that is, the elements themselves are comparable.
3.Comparator vs Comparable
Comparator
and Comparable
They are very similar, but they also have some differences, mainly in the following:
- Different perspectives,
Comparable
It is usually a comparison attribute that comes with the objectComparator
It is usually compared as a "third party". - usually
Comparable
Needs to be implemented by objects to be used as features, andComparator
More like strategy. - one in
java.lang
Under the package, one is injava.util
Next, this also proves the first rule from the side.
4. summary
In summary, if the ordering of objects needs to be based on natural order (which is itself comparable), use the Comparable
, and if you need to sort different attributes based on your business, use the Comparator
。
Comments0