import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Comparator;
class Student implements Comparable<Student>{
String name;
int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public int getAge() {
return this.age;
}
@Override
public String toString(){
return name + "-" + age;
}
@Override
public int compareTo(Student o) {
if (this.age > o.age){
return 1;
} else {
return -1;
}
}
}
public class test2 {
public static void main(String[] args) {
List<Student> list = new ArrayList<>();
Student s1 = new Student("shallow", 25);
Student s2 = new Student("feather", 23);
Student s3 = new Student("lll", 22);
Collections.addAll(list, s1, s2, s3);
Collections.sort(list, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.compareTo(o2);
}
});
System.out.println(list.toString());
}
}
解释:
- o1是后面值,o2是前面的值,如下图:
![在这里插入图片描述](https://img-blog.csdnimg.cn/5623723d88ff45b68bf298eb9f328641.png)
- 返回值为-1,表示交换,返回值为1表示不交换。