注意:
1.使用TreeSet集合存储对象,带参构造方法利用比较器对元素排序
2.在TreeSet集合的构造方法接受Comparator的实现类对象,重写compare方法
测试样例
public static void main(String[] args) {
TreeSet<Student> t= new TreeSet<Student>(new Comparator<Student>(){
@Override
public int compare(Student s1, Student s2){
int count=s1.getAge()-s2.getAge();
int number=count==0?s1.getName().compareTo(s2.getName()):count;
return number;
}
});
Student s1= new Student("奥特曼",500);
Student s2= new Student("葫芦娃",20);
Student s3= new Student("王铁锤",17);
Student s4= new Student("xt",21);
Student s5= new Student("alen",21);
Student s6= new Student("alen",21);
//添加学生到集合
t.add(s1);
t.add(s2);
t.add(s3);
t.add(s4);
t.add(s5);
t.add(s6);
for(Student s:t){
System.out.println(s.getName()+","+s.getAge());
}
结果