时间:2022-09-27 11:11:42 | 栏目:JAVA代码 | 点击:次
需求:用TreeSet集合存储多个学生信息(姓名,语文成绩,数学成绩),并遍历该集合;要按照总分从高到低进行排序
分析:
get\set方法TreeSet集合对对象,并使用内部类的方式重写compare方法要定好排序规则,主要条件按照总分从高到底排序,在总分相同的情况下按照语文成绩排序,在两者都相同的情况下判断姓名是否相同,相同就不存储,不相同存进来,按照姓名字母进行排序
add方法将学生数据加入到TreeSet集合中代码实现:
Student类
public class Student {
//成员变量
private String name;
private int YWscore;
private int YYscore;
?
//构造方法
public Student(){}
?
public Student(String name, int YWscore, int YYscore) {
this.name = name;
this.YWscore = YWscore;
this.YYscore = YYscore;
}
//get/set方法
?
public String getName() {
return name;
}
?
public void setName(String name) {
this.name = name;
}
?
public int getYWscore() {
return YWscore;
}
?
public void setYWscore(int YWscore) {
this.YWscore = YWscore;
}
?
public int getYYscore() {
return YYscore;
}
?
public void setYYscore(int YYscore) {
this.YYscore = YYscore;
}
//定义求总成绩方法
public int getSum(){
int sum=YWscore+YYscore;
return sum;
}
}
?
测试类
public class StudentDemo {
public static void main(String[] args) {
//创建TreeSet集合对象
TreeSet<Student>ts=new TreeSet<Student>(new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
// return 0;
int num=s2.getSum()-s1.getSum();//要从高到底排序
int num1= num==0?s1.getYWscore()-s2.getYWscore():num;//当总分相同时按照语文成绩排序
int num2= num1==0?s1.getName().compareTo(s2.getName()):num1;
return num2;
}
});
//创建学生对象
Student s1=new Student("张三",56,66);
Student s2=new Student("张四",70,69);
Student s3=new Student("张五",80,76);
Student s4=new Student("张六",66,96);
Student s5=new Student("张七",66,96);
ts.add(s5);
ts.add(s1);
ts.add(s2);
ts.add(s3);
ts.add(s4);
//遍历
for (Student ss:ts){
System.out.println(ss.getName()+","+ss.getYWscore()+","+ss.getYYscore()+","+ss.getSum());
}
}
}