本帖最后由 龚首道 于 2013-8-24 20:02 编辑
如题,我有以下所示代码,为什么我遍历后,Map.Entry的getKey返回的是hash值。为什么?- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.Map;
- import java.util.Set;
- public class HashMapDemo {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- HashMap<Student,String> hshmp = new HashMap<Student,String>();
- hshmp.put(new Student("gong",22), "shanghai");
- hshmp.put(new Student("haohao",23), "beijing");
-
- Set<Map.Entry<Student,String>> me = hshmp.entrySet();
- for(Iterator<Map.Entry<Student,String>> it = me.iterator();it.hasNext();)
- {
- Map.Entry<Student, String> mapentr = it.next();
- Student stu = mapentr.getKey();
- System.out.println("Stu:"+stu+",add:"+mapentr.getValue());
- }
- }
- }
- class Student implements Comparable<Student>
- {
- private String name;
- private int age;
- public Student(String n,int a)
- {
- this.name = n;
- this.age = a;
-
- }
- public void setAge(int a)
- {
- this.age = a;
- }
- public int getAge()
- {
- return this.age;
- }
- public void setName(String n)
- {
- this.name = n;
- }
- public String getName()
- {
- return this.name;
- }
- @Override
- public int compareTo(Student o) {
- // TODO Auto-generated method stub
- int num = new Integer(this.age).compareTo(new Integer(o.age));
- if(num == 0)
- return (this.name).compareTo(o.name);
- return num;
- }
- @Override
- public boolean equals(Object obj)
- {
- if(!(obj instanceof Student))
- throw new ClassCastException("类型异常");
- Student stu = (Student)obj;
- return this.name.equals(stu.name) && this.age == stu.age;
- }
- public int hashCode()
- {
- return name.hashCode()+age*34;
- }
-
- }
复制代码 |