import java.util.*;
class Student implements Comparable<Student>
{
private String name;
private int age;
Student(String name,int age)
{
this.name=name;
this.age=age;
}
public int hashCode()
{
return name.hashCode()+age*34;
}
public boolean equals(Object obj)
{
if(! (obj instanceof Student))
throw new ClassCastException("类型不对");
Student s =(Student)obj;
return this.name.equals(s.name) && this.age==s.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 String getName()
{
return name;
}
public int getAge()
{
return age;
}
}
class MapTest
{
public static void main(String[] args)
{
HashMap<Student,String> hm =new HashMap<Student,String>();
hm.put(new Student("zhangsan",1),"bj");
hm.put(new Student("lisi",2),"sh");
hm.put(new Student("wangwu",1),"gz");
Set<Map.Entry<Student,String>> entrySet = hm.entrySet();
Iterator<Map.Entry<Student,String>> it = entrySet.iterator();
while(it.hasNext())
{
Map.Entry<Student,String> me = it.next();
Student stu = me.getKey();
String add = me.getValue();
System.out.println(stu+".."+add);
}
}
}
为什么打印的结果是这样?
Student@aa9c3096..bj
Student@d09b2c43..gz
Student@32b0d7..sh |