TreeSet对象排序:创建学生类 属性包括姓名,年龄,Java成绩,英语成绩。 创建5个学生对象,存入TreeSet集合中,排序规则是: 按总分从高到低; 如果总分一样,按Java成绩排序; 如果Java成绩一样,按年龄排序; 如果年龄一样,按姓名的字母顺序排序。 如果都一样,认为是同一个学生,不存。
时间: 2023-06-02 21:05:46 浏览: 154
Java集合框架总结:TreeSet类的排序问题
5星 · 资源好评率100%
好的,这个问题比较简单,我可以回答。请先看一下我给出的代码实现:
```java
import java.util.*;
class Student implements Comparable<Student>{
String name;
int age;
int javaScore;
int englishScore;
public Student(String name, int age, int javaScore, int englishScore) {
this.name = name;
this.age = age;
this.javaScore = javaScore;
this.englishScore = englishScore;
}
public int compareTo(Student other) {
int totalScore = this.javaScore + this.englishScore;
int otherTotalScore = other.javaScore + other.englishScore;
if(totalScore != otherTotalScore) {
return otherTotalScore - totalScore;
} else if(this.javaScore != other.javaScore) {
return other.javaScore - this.javaScore;
} else if(this.age != other.age) {
return this.age - other.age;
} else {
return this.name.compareTo(other.name);
}
}
public boolean equals(Object obj){
if(obj instanceof Student){
Student other=(Student)obj;
return this.name.equals(other.name) && this.age == other.age && this.javaScore == other.javaScore && this.englishScore == other.englishScore;
}
return super.equals(obj);
}
public int hashCode(){
return Objects.hash(name, age, javaScore, englishScore);
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student("张三", 18, 90, 80);
Student s2 = new Student("李四", 17, 80, 90);
Student s3 = new Student("王五", 18, 90, 70);
Student s4 = new Student("赵六", 18, 90, 80);
Student s5 = new Student("陈七", 19, 80, 90);
TreeSet<Student> set = new TreeSet<>();
set.add(s1);
set.add(s2);
set.add(s3);
set.add(s4);
set.add(s5);
for(Student s : set) {
System.out.println(s.name + " " + s.age + " " + s.javaScore + " " + s.englishScore);
}
}
}
```
我重写了Student类的compareTo方法,以便排序。我们需要先将学生对象存入TreeSet集合中,然后输出集合中的元素即可。按照规则,输出结果应该是这样的:
```
张三 18 90 80
赵六 18 90 80
陈七 19 80 90
王五 18 90 70
李四 17 80 90
```
如果你有任何问题,可以继续问我。
阅读全文