就比如下面这个程序:
import java.util.*;
public class HashtableTest
{
public static void main(String []args)
{
Hashtable numbers=new Hashtable();
numbers.put(new MyKey("zhangsan",18),new Integer(1));
numbers.put(new MyKey("Lisi",15),new Integer(2));
numbers.put(new MyKey("Wangwu",20),new Integer(3));
Enumeration e=numbers.keys();
while(e.hasMoreElements())
{
MyKey key=(MyKey)e.nextElement();
System.out.print(key.toString()+"=");
System.out.println(numbers.get(key).toString());
}
}
}
class MyKey
{
private String name;
private int age;
public MyKey(String name,int age)
{
this.name=name;
this.age=age;
}
public String toString()
{
return new String(name+","+age);
}
public boolean equals(Object obj)
{
MyKey m=(MyKey)obj;
if(name.equals(m.name)&& age==m.age)
return true;
else
return false;
}
public int hashCode()
{
return name.hashCode()+age;//就是这里,为什么要+age??
}
}
谢谢!