如何在Java中定义一个名为Student的类,该类具有属性如学号(id)、姓名(name)和总成绩(totalScore),并创建多个Student对象?接着,请使用TreeSet对这些Student对象按照总成绩降序排列,最后如何遍历并输出排好序的学生列表?
时间: 2024-11-30 15:28:41 浏览: 0
在Java中,你可以首先定义一个`Student`类,如下所示:
```java
public class Student {
private String id;
private String name;
private double totalScore;
// 构造函数
public Student(String id, String name, double totalScore) {
this.id = id;
this.name = name;
this.totalScore = totalScore;
}
// 获取和设置属性的方法
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public double getTotalScore() { return totalScore; }
public void setTotalScore(double totalScore) { this.totalScore = totalScore; }
@Override
public String toString() {
return "Student{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", totalScore=" + totalScore +
'}';
}
}
```
然后,你可以创建多个`Student`对象,例如:
```java
Student student1 = new Student("001", "张三", 85);
Student student2 = new Student("002", "李四", 92);
Student student3 = new Student("003", "王五", 78);
// 更多学生对象...
```
接下来,你可以使用`TreeSet`,它会自动根据元素的自然顺序(这里是`double`类型的降序)来排序:
```java
TreeSet<Student> sortedStudents = new TreeSet<>((s1, s2) -> Double.compare(s2.getTotalScore(), s1.getTotalScore()));
sortedStudents.add(student1);
sortedStudents.add(student2);
sortedStudents.add(student3);
// 添加其他学生
for (Student student : sortedStudents) {
System.out.println(student.toString());
}
```
阅读全文