5、用匿名内部类对集合中的元素实现自定义排序,要求: 1)定义学生类(学号,姓名、成绩); 2)定义集合,在集合里添加4个学生对象; 3)按照成绩从低到高进行排序; 4)如果年龄相同则按照姓名的长度进行排序
时间: 2024-03-10 10:46:50 浏览: 75
以下是实现自定义排序的代码示例:
```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Main {
public static void main(String[] args) {
// 定义学生类(学号,姓名、成绩)
class Student {
private int id;
private String name;
private int score;
public Student(int id, String name, int score) {
this.id = id;
this.name = name;
this.score = score;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getScore() {
return score;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", score=" + score +
'}';
}
}
// 定义集合,在集合里添加4个学生对象
List<Student> students = new ArrayList<>();
students.add(new Student(1, "Tom", 80));
students.add(new Student(2, "Jack", 90));
students.add(new Student(3, "Bob", 70));
students.add(new Student(4, "Ann", 80));
// 按照成绩从低到高进行排序;如果成绩相同则按照姓名的长度进行排序
Collections.sort(students, new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
if (s1.getScore() == s2.getScore()) {
return s1.getName().length() - s2.getName().length();
} else {
return s1.getScore() - s2.getScore();
}
}
});
// 打印排序后的学生列表
System.out.println(students);
}
}
```
输出结果为:
```
[Student{id=3, name='Bob', score=70}, Student{id=1, name='Tom', score=80}, Student{id=4, name='Ann', score=80}, Student{id=2, name='Jack', score=90}]
```
阅读全文