Introduce
The actual needs of using Java comparators, ordinary comparison operators can only compare basic data types, if you want to compare reference data types, it can do nothing.
For example, when buying things, we sometimes need to sort by sales, by the number of reviews, and by price. Each product here is an object. If we want to achieve our sorting requirements, then we will use Java to compare Device
1. Natural sorting
Like String, wrapper classes all implement the Comparable interface, rewrite the ComparTo method, and give a method to compare two objects
重写CompareTo方法的规则:
如果当前对象this大于形参对象obj,则返回正整数
如果当前对象this小于形参对象obj,则返回负整数
如果当前对象this等于形参对象obj,则返回零
For custom classes, if you want to sort, we can make the custom class implement the Comparable interface, override the ComparTo method, specify how to sort in the method body, usually we call this sort of natural sort
//实现Comparable接口
class Order implements Comparable<Goods>{
//重写compareTo方法
@override
public int compareTo(Goods o){
if (this.price > o.price){
return 1;
}else if (this.price < o.price){
return -1;
}else{
return this.name.compareTo(o.name);
}
}
}
Two, custom sort
When the type of element does not implement the Comparable interface and it is not convenient to modify the code,
Or the collation that implements the Comparable interface is not suitable for the current operation,
Then you can consider using Comparator's objects to sort, and forcibly compare multiple objects in overall sorting
Goods[] goods = new Goods[3];
goods[0] = new Goods("dhak",56);
goods[1] = new Goods("jdask",12);
goods[2] = new Goods("xa",20);
Arrays.sort(goods, new Comparator<Goods>() {
@Override
public int compare(Goods o1, Goods o2) {
return o1.compareTo(o2);
}
});