用TreeSet集合存储多个学生信息(姓名,语文成绩,数学成绩),并遍历该集合
要求:按照总分从高到低出现
学生成绩类
public class StudentScore{
public static void main(String[] args){
private String name;
private int cscore;//语文成绩;
private int mscore;//数学成绩;
public class StudentScore(){}
public class StudentScore(String name,int cscore, int mscore){
this.name = name;
this.cscore = CScore;
this.mscore = MScore
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public int getCscore(){
return cscore;
}
public void setCscore(int mscore){
this.cscore = cscore;
}
public int getMscore(){
return mscore;
}
public void setMscore(int mscore){
this.mscore = mscore;
}
public int getSum(){
return this.cscore + this.mscore;
}
测试类
public class Demo{
public static void main(String[] args){
TreeSet<StudentScore> ts = new TreeSet<StudentScore>(new Comparator<StudentScore>){
@Override
public int compare(Student s1,Student s2){
int num = s1.getSum() - s2.getSum();
//次要条件
//当总分相同时比较语文分数
int num2 = num == 0 ? s1.getChinese() - s2.getChinese() : num;
//当总分相同+语文分数相同:比较姓名是否相同
int num3 = num2 == 0 ? s1.getName().compareTo(s2.getName()) : num2;
return num3;
}
}
//创建学生对象
StudentScore s1 = new Student("a", 90, 90);
StudentScore s2 = new Student("b", 92, 90);
StudentScore s3 = new Student("c", 93, 90);
StudentScore s4 = new Student("d", 98, 90);
StudentScore s5 = new Student("f", 81, 90);
StudentScore s6 = new Student("g", 77, 90);
for (StudentScore s : ts) {
System.out.println(s.getName() + "," + s.getCscore() + "," + s.getMscore() + "," + s.getSum());
}
}
}