实现思路
- 定义
Student
类,实现Comparable
接口,在compareTo
方法中根据成绩进行比较。
- 使用
TreeMap
来存储Student
对象,TreeMap
会根据键的自然顺序(这里是Student
对象基于成绩的比较顺序)进行排序。
关键代码片段
import java.util.Map;
import java.util.TreeMap;
class Student implements Comparable<Student> {
private String name;
private int score;
public Student(String name, int score) {
this.name = name;
this.score = score;
}
@Override
public int compareTo(Student other) {
return this.score - other.score;
}
public String getName() {
return name;
}
public int getScore() {
return score;
}
}
public class StudentTreeMap {
public static void main(String[] args) {
Map<Student, Integer> studentMap = new TreeMap<>();
studentMap.put(new Student("Alice", 85), 1);
studentMap.put(new Student("Bob", 78), 2);
studentMap.put(new Student("Charlie", 92), 3);
for (Map.Entry<Student, Integer> entry : studentMap.entrySet()) {
Student student = entry.getKey();
System.out.println("Name: " + student.getName() + ", Score: " + student.getScore());
}
}
}