对TreeSet中存储的自定义类的对象进行排序
步骤:
- 1 自定义类实现Comparable接口,重写compareTo方法
- 2 方法内:
主要条件:按照学生的总成绩进行排序(从高到低)
次要条件:总成绩相同,排序数学成绩;数学成绩相同,排序语文成绩;语文成绩相同,排序年龄;年龄相同,排序姓名(姓名排序使用的是String类的compareTo方法,内部计算字符的码表差值[0-9A-Za-z])
Case_Student类:
package my_set.my_set_case;
public class Case_Student implements Comparable<Case_Student>{
private String name;
private int age;
private int mathScore;
private int ChineseScore;
private int EnglishScore;
private int allScore ;
public Case_Student() {
}
public Case_Student(String name, int age, int mathScore, int chineseScore, int englishScore) {
this.name = name;
this.age = age;
this.mathScore = mathScore;
this.ChineseScore = chineseScore;
this.EnglishScore = englishScore;
this.allScore = mathScore + chineseScore + englishScore;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getMathScore() {
return mathScore;
}
public void setMathScore(int mathScore) {
this.mathScore = mathScore;
}
public int getChineseScore() {
return ChineseScore;
}
public void setChineseScore(int chineseScore) {
ChineseScore = chineseScore;
}
public int getEnglishScore() {
return EnglishScore;
}
public void setEnglishScore(int englishScore) {
EnglishScore = englishScore;
}
public int getAllScore() {
return allScore;
}
public void setAllScore(int allScore) {
this.allScore = allScore;
}
@Override
public String toString() {
return "Cast_Student{" +
"name='" + name + '\'' +
", age=" + age +
", mathScore=" + mathScore +
", ChineseScore=" + ChineseScore +
", EnglishScore=" + EnglishScore +
", allScore=" + allScore +
'}';
}
@Override
public int compareTo(Case_Student o) {
int i = o.getAllScore() - this.getAllScore();
if (i==0){
i = o.getMathScore() - this.getMathScore();
}
if (i==0){
i = o.getChineseScore() - this.getChineseScore();
}
if (i==0){
i = o.getAge() - this.getAge();
}
if (i==0){
i = o.getName().compareTo(this.getName());
}
return i;
}
}
Case_Test类:
package my_set.my_set_case;
//先比较总成绩,按照从大到小排序;如果相同,排序数学成绩;如果相同,排序语文成绩;如果相同,排序年龄;如果相同,排序姓名
import java.util.TreeSet;
public class Case_Test {
public static void main(String[] args) {
TreeSet<Case_Student> students = new TreeSet<Case_Student>();
students.add(new Case_Student("张三",18,86,84,85));
students.add(new Case_Student("李四",19,90,84,91));
students.add(new Case_Student("王五",21,99,100,60));
students.add(new Case_Student("张三",18,86,84,85));
students.add(new Case_Student("老六",18,84,86,85));
students.add(new Case_Student("老八",17,84,86,85));
for (Case_Student student : students) {
System.out.println(student);
}
}
}