本帖最后由 李征 于 2013-5-12 23:40 编辑
请问在覆盖hashCode方法的时候,毕老师为什么要在age后面*34呢?始终不理解,有没有高手帮小弟解答一下,感激不尽!
代码如下:
import java.util.*;
class MapDemo
{
public static void main(String[] Args)
{
HashMap<Student,String> hm= new HashMap<Student,String>();
hm.put(new Student("lisi1",21),"beijing");
hm.put(new Student("lisi1",21),"beng");
hm.put(new Student("lisi2",22),"beijin");
hm.put(new Student("lisi3",23),"beiji");
//第一种取出方式 keySet
Set<Student> keySet = hm.keySet();
Iterator<Student> it = keySet.iterator();
while(it.hasNext())
{
Student stu = it.next();
String addr = hm.get(stu);
System.out.println(stu+".."+addr);
}
//第二种取出方式 entrySet
Set<Map.Entry<Student,String>> entrySet = hm.entrySet();
Iterator<Map.Entry<Student,String>> iter = entrySet.iterator();
while(iter.hasNext())
{
Map.Entry<Student,String> me = iter.next();
Student stu = me.getKey();
String addr = me.getValue();
System.out.println(stu+" "+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()//覆盖2个方法
{
return name.hashCode()+age*34;//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 String getName()
{
return name;
}
public int getAge()
{
return age;
}
public String toString()
{
return "name:"+name+"age:"+age;
}
} |
|