import java.util.Comparator;
import java.util.TreeSet;
/*比较器排序Comparator的使用
实例:存储学生对象
要求:年龄按照从小到大进行排序,当年龄相同是按照姓名的字母进行排序
* */
public class homework1 {
public static void main(String[] args) {
TreeSet<student> t=new TreeSet<student>(new Comparator<student>() {//匿名内部类
@Override
public int compare(student o1, student o2) {
//return 0;
int num= o1.getAge()-o2.getAge();
int num2=num==0?o1.getName().compareTo(o2.getName()):num;
return num2;
}
});
student s1=new student("wangzhaojun",25);
student s2=new student("diaochan",26);
student s3=new student("yangyuhuan",30);
student s4=new student("xishi",30);
t.add(s1);
t.add(s2);
t.add(s3);
t.add(s4);
//遍历集合
for(student a:t){
System.out.println(a.getName()+","+a.getAge());
}
}
}
public class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}