编写一个JAVA程序,将原来存放在LinkList链表中的学生英语成绩单(包含学生姓名,英语成绩属性)存放到一个TreeSet中,使得按成绩自动排序,并输出排序结果
时间: 2024-02-20 08:01:11 浏览: 67
java毕业设计之ArrayList,LinkList链表接口实现源码.zip
可以参考以下代码实现:
```java
import java.util.*;
class Student implements Comparable<Student> {
private String name;
private int score;
public Student(String name, int score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public int getScore() {
return score;
}
@Override
public int compareTo(Student o) {
return Integer.compare(this.score, o.score);
}
@Override
public String toString() {
return name + ": " + score;
}
}
public class Main {
public static void main(String[] args) {
LinkedList<Student> students = new LinkedList<>();
students.add(new Student("Alice", 80));
students.add(new Student("Bob", 90));
students.add(new Student("Charlie", 70));
students.add(new Student("David", 85));
students.add(new Student("Eva", 75));
TreeSet<Student> sortedStudents = new TreeSet<>();
sortedStudents.addAll(students);
System.out.println("Sorted by score:");
for (Student student : sortedStudents) {
System.out.println(student);
}
}
}
```
运行结果:
```
Sorted by score:
Charlie: 70
Eva: 75
Alice: 80
David: 85
Bob: 90
```
阅读全文