public class Person implements Comparable<Person>{
private String name;
private int age;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String toString(){
return name+"-"+age;
}
public int compareTo(Person o) {
int num=new Integer(this.age).compareTo(new Integer(o.age));
if(num==0){
return this.name.compareTo(o.name);
}
return num;
}
public int hashCode(){
return name.hashCode()+age*30;
}
public boolean equals(Object ob) {
if (!(ob instanceof Person)) {
throw new ClassCastException("不是Person对象");
}
Person p = (Person) ob;
return this.name.equals(p.name) && this.age == p.age;
}
public static void main(String [] s){
HashMap<Person,String> map=new HashMap<Person,String>();
map.put(new Person("zs1",22), "北京");
map.put(new Person("zs2",23), "上海");
map.put(new Person("zs3",23), "天津");
map.put(new Person("zs4",24), "邯郸");
map.put(new Person("zs4",24), "张家口");
Set<Person> keys= map.keySet();
Iterator<Person> it=keys.iterator();
while(it.hasNext()){
Person p=it.next();
System.out.println("键:"+p.toString()+" 值:"+map.get(p));
}
}
}结果:
键:zs3-23 值:天津键:zs4-24 值:张家口键:zs2-23 值:上海键:zs1-22 值:北京
为什么结构的键不排序呢,实现接口 Comparable<Person>不就是为了让Person自身具有比较性吗,hashCode()和equals()方法是为了不能有重复的值,那为什么结果键不具有排序呢。
实现接口 Comparable<Person>的作用??
请各位指教!
|