当key是Student类对象,value是String型时,
(一) 在Student类中重写compareTo方法
@Override
public int compareTo(student o) {
int num=this.age-o.age;
return num==0?this.name.compareTo(o.name):num;
}
回到主函数,
public static void demo1() {
TreeMap<student,String> tm=new TreeMap<student,String>();
tm.put(new student("张三",23), "北京");
tm.put(new student("赵六",13), "上海");
tm.put(new student("李四",24), "广州");
tm.put(new student("王五",25), "深圳");
System.out.println(tm);
}
(二)传入比较器Comparator《E》
public static void demo2() {
TreeMap<student,String> tm=new TreeMap<student,String>(
new Comparator<student>(){
@Override
public int compare(student s1, student s2) {
int num=s1.getName().compareTo(s2.getName());
return num==0?s1.getAge()-s2.getAge():num;
}
});
tm.put(new student("张三",23), "北京");
tm.put(new student("赵六",13), "上海");
tm.put(new student("李四",24), "广州");
tm.put(new student("王五",25), "深圳");
System.out.println(tm);
}