import java.util.*;
/**
学生Student 地址addr 属性:姓名,年龄
注:姓名和年龄相同为同一个学生
保证学生唯一性
对学生按年龄升序排序
*/
class Student implements Comparable{
private int age;
private String name;
public int compareTo(Object obj){
Student s = (Student)obj;
int num = this.getName().compareTo(s.getName());
if(num==0){
return this.getAge()-s.getAge();
}
else
return num;
}
//唯一性判断
public int hashCode(){
return name.hashCode()+age*12;
}
public boolean equals(Object obj){
if(!(obj instanceof Student))
throw new ClassCastException("不是学生对象!");
Student st = (Student)obj;
return this.name == st.name && this.age==st.age;
}
Student(String name,int age){
this.age = age;
this.name = name;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
}
//自定义比较器
class MyCom implements Comparator<Student>{//接收比较对象的类型是学生类
public int compare(Student s1 ,Student s2 ){
int num = s1.getAge()-s2.getAge();
if(num==0){
return s1.getName().compareTo(s2.getName());
}
else
return num;
}
}
class TreeMapTest{
public static void main(String[]args){
TreeMap<Student,String> hm = new TreeMap<Student,String>();
hm.put(new Student("李四1",21),"北京");
hm.put(new Student("李四2",22),"广州");
hm.put(new Student("李四2",25),"广州");
hm.put(new Student("李四3",23),"杭州");
Set<Student> ky = hm.keySet();
Iterator<Student> it=ky.iterator();
while(it.hasNext()){
Student stu = it.next();
String addr = hm.get(stu);
System.out.println("学生姓名:"+stu.getName()+",年龄:"+stu.getAge()+",地址:"+addr);
}
}
}
转载于:https://blog.51cto.com/9274590/1701628