TreeSet集合比较器Comparator排序的使用
1.为保证唯一性需要重新定义比较器,添加主要判断条件以及次要判断条件。
2.通过加强for循环来遍历集合中的数据。
实践了黑马程序员中P248:成绩排序 的案例
Student类
******************
public class Student {
private int Chinese;
private int Math;
private String Name ;
public Student() {
}
public Student(String Name, int Chinese, int Math) {
this.Name = Name;
this.Math = Math;
this.Chinese = Chinese;
}
public int getChinese() {
return Chinese;
}
public void setChinese(int chinese) {
this.Chinese = chinese;
}
public int getMath() {
return Math;
}
public void setMath(int math) {
this.Math = math;
}
public String getName() {
return Name;
}
public void setName(String name) {
this.Name = name;
}
public int getnum() {
return this.Chinese + this.Math;
}
}
TreeSetDemo
*******************************
import java.util.Comparator;
import java.util.TreeSet;
public class TreeSetDemo {
public static void main(String[] args) {
// 重新定义比较器
TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
int num = s1.getnum() - s2.getnum();
int num1 = num == 0 ? s1.getName().compareTo(s2.getName()):num;
return num1;
}
});
// 创造对象
Student s1 = new Student("a",90,98);
Student s2 = new Student("b",90,98);
Student s3 = new Student("c",95,98);
Student s4 = new Student("d",94,96);
Student s5 = new Student("e",99,99);
Student s6 = new Student("f",99,100);
// 添加独对象
ts.add(s1);
ts.add(s2);
ts.add(s3);
ts.add(s4);
ts.add(s5);
ts.add(s6);
// 遍历
for(Student g : ts){
System.out.println("姓名:"+g.getName() + ","+"数学成绩:"+g.getMath()+",语文成绩:"+g.getChinese());
}
}
}