import java.util.*;
class MapText
{
public static void main(String[] args)
{
HashMap<Student,String> hm=new HashMap<Student,String>();
hm.put(new Student("zhangsan",20),"shanghai");
hm.put(new Student("lisi",25),"tianjing");
System.out.println(hm.put(new Student("zhangsan",20),"jiangxi"));
// hm.put(new Student("zhangsan",20),"jiangxi");
hm.put(new Student("wangwu",23),"nanjing");
// System.out.println(hm);
Set<Student> keySet=hm.keySet();
for (Iterator<Student> it= keySet.iterator();it.hasNext() ; )
{
Student s=it.next();
String addr=hm.get(s);
System.out.println(s+"是"+addr+"的人!");
}
}
}
class Student implements Comparable<Student>
{
private String name;
private int age;
Student(String name,int age)
{
this.name=name;
this.age=age;
}
public int compareTo(Student s)
{
int num= new Integer(this.age).compareTo(new Integer(s.age));
if (num==0)
{
return this.name.compareTo(s.name);
}
return num;
}
public int hashCode()
{
return name.hashCode()+age*24;
}
public boolean equals(Object o)
{
if (!(o instanceof Student))
{
throw new ClassCastException("类型不匹配!");
}
Student s= (Student)o;
return this.name.equals(s.name)&& this.age==s.age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public String toString()
{
return name+".."+age;
}
}
jiangxi
wangwu..23是nanjing的人!
lisi..25是tianjing的人!
zhangsan..20是jiangxi的人!
hm.put(new Student("zhangsan",20),"shanghai");先进去。
System.out.println(hm.put(new Student("zhangsan",20),"jiangxi"));后进去,
红色部分,按道理返回的是shanghai,怎么会是jiangxi 呢? |