之前讲了外部排序,他是需要我们在Student类中写排序的方法,但是很多时候需求要求我们不能去修改别的代码,但是还要完成别人的需求.
所以外部排序就是在不修改别的类的同时,完成排序需求.
package Comparator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class ComparatorDemo {
public static void main(String[] args) {
//泛型 用<>表示 他是为了限制集合里没存放的元素类型
//后面的<>可写可不写
ArrayList<Student> list = new ArrayList<Student>();
//添加
list.add(new Student("小李", 20, 85, "陕西"));
list.add(new Student("小李", 20, 86, "北京"));
list.add(new Student("小李", 21, 89, "榆林"));
list.add(new Student("小李", 19, 92, "安康"));
list.add(new Student("小李", 22, 76, "上海"));
//按照年龄进行排序
//如果年龄相同,按照分数降序排序
//使用外部排序 ,外部排序比内部排序更加严格,他不需要在Student类中写需求
Collections.sort(list, new Comparator<Student>() {
@Override
public int compare(Student t1, Student t2) {
if(t1.getAge()==t2.getAge()){
//我们是要根据分数去排序
//this.grade(你想去比较的字段)-that.grade;这个是升序
return t2.getGrade()-t1.getGrade();
}else{
return t1.getAge()-t2.getAge();
}
}
});
for (Student student : list) {
System.out.println(student);
}
}
}
```java
package Comparator;
public class Student {
private String name;
private int age;
private int grade;
private String address;
public Student() {
}
public Student(String name, int age, int grade, String address) {
this.name = name;
this.age = age;
this.grade = grade;
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", grade=" + grade +
", address='" + address + '\'' +
'}';
}
}