给个java示例,对一组学生对象进行排序,先按照年龄排序,假如年龄一样,就按照成绩排序
时间: 2023-06-03 08:07:13 浏览: 34
好的,以下是一个Java示例,可以对一组学生对象进行排序,先按照年龄排序,假如年龄一样,就按照成绩排序:
```
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
class Student {
private String name;
private int age;
private int score;
public Student(String name, int age, int score) {
this.name = name;
this.age = age;
this.score = score;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public int getScore() {
return score;
}
}
public class SortDemo {
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<>();
students.add(new Student("Tom", 18, 80));
students.add(new Student("Jack", 20, 90));
students.add(new Student("Lucy", 18, 85));
students.add(new Student("Mike", 19, 87));
Collections.sort(students, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
if (o1.getAge() < o2.getAge()) {
return -1;
} else if (o1.getAge() > o2.getAge()) {
return 1;
} else {
if (o1.getScore() < o2.getScore()) {
return -1;
} else if (o1.getScore() > o2.getScore()) {
return 1;
} else {
return 0;
}
}
}
});
for (Student student : students) {
System.out.println(student.getName() + " " + student.getAge() + " " + student.getScore());
}
}
}
```