简介
Comparable<> 接口
Compatator 也是接口 -- 类似C++中的cmp函数.
分别对一个对象实现了 从大到小排序和从小到大排序
code
import java.util.*;
/**
* Created by lee on 2021/6/28.
*/
public class Compara {
public static void main(String[] args) {
List<Person1> v = new ArrayList<>();
for(int i=0; i<100; i++) {
Person1 p= new Person1(i);
v.add(p);
}
Collections.sort(v);
for(int i=0; i<10; i++){
System.out.println(v.get(i));
}
System.out.println("=========================================");
Collections.sort(v, new Comparator<Person1>() {
@Override
public int compare(Person1 o1, Person1 o2) {
return o2.age - o1.age;
}
});
for(int i=0; i<10; i++){
System.out.println(v.get(i));
}
}
}
class Person1 implements Comparable<Person1> {
public int age;
public Person1(int a){
age = a;
}
@Override
public int compareTo(Person1 o) {
return this.age - o.age ;
}
@Override
public String toString() {
return ""+age;
}
}