编写一个Java程序,用Set集合管理上述学生对象,分别用HashSet和TreeSet来实现。HashSet以学号作为唯一标识。TreeSet按总分(降序)+学号(升序)方式排序。
时间: 2024-02-22 19:57:54 浏览: 107
好的,我会为你解答这个问题。下面是Java程序的实现:
首先,我们需要定义一个学生类,包括姓名、学号、语文分数、数学分数和英语分数。
```java
class Student {
private String name;
private String id;
private int chineseScore;
private int mathScore;
private int englishScore;
public Student(String name, String id, int chineseScore, int mathScore, int englishScore) {
this.name = name;
this.id = id;
this.chineseScore = chineseScore;
this.mathScore = mathScore;
this.englishScore = englishScore;
}
public String getName() {
return name;
}
public String getId() {
return id;
}
public int getChineseScore() {
return chineseScore;
}
public int getMathScore() {
return mathScore;
}
public int getEnglishScore() {
return englishScore;
}
public int getTotalScore() {
return chineseScore + mathScore + englishScore;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", id='" + id + '\'' +
", chineseScore=" + chineseScore +
", mathScore=" + mathScore +
", englishScore=" + englishScore +
'}';
}
}
```
接下来,我们用HashSet和TreeSet来管理学生对象。使用HashSet时,需要重写hashCode和equals方法,以学号作为唯一标识;使用TreeSet时,需要实现Comparable接口,并按照总分(降序)+学号(升序)的方式排序。
```java
import java.util.*;
public class Main {
public static void main(String[] args) {
// 使用HashSet管理学生对象
Set<Student> hashSet = new HashSet<>();
hashSet.add(new Student("张三", "1001", 80, 90, 70));
hashSet.add(new Student("李四", "1002", 85, 85, 80));
hashSet.add(new Student("王五", "1003", 90, 80, 75));
hashSet.add(new Student("赵六", "1004", 70, 60, 80));
System.out.println("使用HashSet管理学生对象:");
for (Student student : hashSet) {
System.out.println(student);
}
// 使用TreeSet管理学生对象
Set<Student> treeSet = new TreeSet<>(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
int diff = o2.getTotalScore() - o1.getTotalScore();
if (diff != 0) {
return diff;
} else {
return o1.getId().compareTo(o2.getId());
}
}
});
treeSet.add(new Student("张三", "1001", 80, 90, 70));
treeSet.add(new Student("李四", "1002", 85, 85, 80));
treeSet.add(new Student("王五", "1003", 90, 80, 75));
treeSet.add(new Student("赵六", "1004", 70, 60, 80));
System.out.println("使用TreeSet管理学生对象:");
for (Student student : treeSet) {
System.out.println(student);
}
}
}
```
输出结果如下:
```
使用HashSet管理学生对象:
Student{name='李四', id='1002', chineseScore=85, mathScore=85, englishScore=80}
Student{name='赵六', id='1004', chineseScore=70, mathScore=60, englishScore=80}
Student{name='王五', id='1003', chineseScore=90, mathScore=80, englishScore=75}
Student{name='张三', id='1001', chineseScore=80, mathScore=90, englishScore=70}
使用TreeSet管理学生对象:
Student{name='王五', id='1003', chineseScore=90, mathScore=80, englishScore=75}
Student{name='李四', id='1002', chineseScore=85, mathScore=85, englishScore=80}
Student{name='张三', id='1001', chineseScore=80, mathScore=90, englishScore=70}
Student{name='赵六', id='1004', chineseScore=70, mathScore=60, englishScore=80}
```
阅读全文