案例1:成绩排序
需求:用TreeSet存储多个学生信息(姓名,语文成绩,数学成绩),并遍历该集合
要求:按照总分从高到低出现
思路:
- 定义学生类
package itheima;
public class Student{
private String name;
private int chinese;
private int math;
public Student() {
}
public Student(String name,int chinese,int math){
this.chinese= chinese;
this.math =math;
this.name =name;
}
public void setName(String name) {
this.name=name;
}
public void setChinese(int chinese) {
this.chinese= chinese;
}
public void setMath(int math) {
this.math =math;
}
public String getName() {return name;}
public int getChinese() {return chinese;}
public int getMath() {return math;}
public int getSum() {
return this.chinese+this.math;
}
}
- 创建TreeSet集合对象,通过比较器进行排序
- 创建学生对象
- 把学生对象添加到集合
- 遍历集合
package itheima;
import java.util.Comparator;
import java.util.TreeSet;
public class TreeSetDemo {
public static void main(String[] args) {
//创建TreeSet集合对象,通过比较器排序进行排序
TreeSet<Student> ts =new TreeSet<Student>(new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
// int num=(s2.getChinese()+s2.getMath())-(s1.getChinese()+s1.getMath());
//主要条件
int num =s2.getSum()-s1.getSum();
//次要条件(重点分析)
int num2= num==0?s1.getChinese()-s2.getChinese():num;
int num3 =num2==0?s1.getName().compareTo(s2.getName()):num2;
return num3;
}
});
//创建学生对象
Student s1 =new Student("小红",67,90);
Student s2 =new Student("小看",90,46);
Student s3 =new Student("小可",67,100);
Student s4=new Student("小将",87,80);
Student s5=new Student("小来",44,99);
Student s6=new Student("大明",99,44);
Student s7=new Student("赵宇",99,44);
ts.add(s5);
ts.add(s4);
ts.add(s3);
ts.add(s2);
ts.add(s6);
ts.add(s7);
for(Student s:ts) {
System.out.println(s.getChinese()+","+s.getMath()+","+s.getName()+","+s.getSum());
}
}
}