用Set集合管理上述学生对象,分别用HashSet和TreeSet来实现。HashSet以学号作为唯一标识。TreeSet按总分(降序)+学号(升序)方式排序。javav程序
时间: 2024-02-18 19:03:35 浏览: 95
HashSet和TreeSet.doc
好的,下面是Java代码实现:
```java
// 学生类(与上面一样)
// 学生管理类
import java.util.*;
public class StudentManager {
private Set<Student> studentSet;
public StudentManager() {
this.studentSet = new HashSet<>(); // 或者 TreeSet
}
// 添加学生
public void addStudent(Student student) {
studentSet.add(student);
}
// 查询学生
public Student getStudent(String id) {
for (Student student : studentSet) {
if (student.getId().equals(id)) {
return student;
}
}
return null;
}
// 删除学生
public boolean deleteStudent(String id) {
Student student = getStudent(id);
if (student != null) {
return studentSet.remove(student);
}
return false;
}
// 获取按总分+学号排序的学生列表
public List<Student> getSortedStudentList() {
List<Student> studentList = new ArrayList<>(studentSet);
Collections.sort(studentList, new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
if (s1.getTotalScore() != s2.getTotalScore()) {
return Double.compare(s2.getTotalScore(), s1.getTotalScore()); // 总分降序
} else {
return s1.getId().compareTo(s2.getId()); // 学号升序
}
}
});
return studentList;
}
}
// 测试类
public class Test {
public static void main(String[] args) {
StudentManager manager = new StudentManager();
// 添加学生
double[] scores1 = {90.0, 85.0, 95.0};
Student student1 = new Student("001", "Tom", scores1);
manager.addStudent(student1);
double[] scores2 = {80.0, 88.0, 92.0};
Student student2 = new Student("002", "Jerry", scores2);
manager.addStudent(student2);
// 查询学生
System.out.println(manager.getStudent("001").getName()); // 输出:Tom
// 删除学生
manager.deleteStudent("002");
// 获取按总分+学号排序的学生列表
List<Student> studentList = manager.getSortedStudentList();
for (Student student : studentList) {
System.out.println(student.getId() + " " + student.getName() + " " + student.getTotalScore());
}
}
}
```
这里我们使用了HashSet和TreeSet两种集合来管理学生实例,分别按学号和总分+学号排序。同时,我们还实现了学生管理的基本功能:添加学生、查询学生、删除学生、获取按总分+学号排序的学生列表。最后,我们使用测试类Test来验证了这些功能的正确性。
阅读全文