剑建一个Student类,包含号号、姓名、成绩三个属性。 1创建多个Student对象,添加到HashSet里面,当学号一样的时候认为是同一个号生,不添加。 2创建对个Student对象,添加到Treeset里面,以成绩进行降市排,当成绩一样是,以学号进行升序排
时间: 2023-07-15 21:14:08 浏览: 43
下面是Java代码实现:
```java
import java.util.HashSet;
import java.util.TreeSet;
public class Student implements Comparable<Student> {
private int id;
private String name;
private double score;
public Student(int id, String name, double score) {
this.id = id;
this.name = name;
this.score = score;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public double getScore() {
return score;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Student) {
Student student = (Student) obj;
return this.id == student.id;
}
return false;
}
@Override
public int hashCode() {
return Integer.hashCode(id);
}
@Override
public int compareTo(Student student) {
if (this.score != student.score) {
return Double.compare(student.score, this.score);
} else {
return Integer.compare(this.id, student.id);
}
}
public static void main(String[] args) {
// 使用HashSet去重
HashSet<Student> set1 = new HashSet<>();
set1.add(new Student(1, "张三", 90));
set1.add(new Student(2, "李四", 85));
set1.add(new Student(3, "王五", 92));
set1.add(new Student(1, "赵六", 88)); // 学号1已存在,不会添加
System.out.println("使用HashSet去重后的学生数量:" + set1.size());
// 使用TreeSet按成绩降序排列,成绩相同按学号升序排列
TreeSet<Student> set2 = new TreeSet<>();
set2.add(new Student(1, "张三", 90));
set2.add(new Student(2, "李四", 85));
set2.add(new Student(3, "王五", 92));
set2.add(new Student(4, "赵六", 88));
set2.add(new Student(5, "钱七", 92)); // 成绩92的学生数量为2,按学号进行升序排列
System.out.println("使用TreeSet按成绩排序后的学生列表:");
for (Student student : set2) {
System.out.println(student.getId() + " " + student.getName() + " " + student.getScore());
}
}
}
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)