代码和问题:
import java.util.*;
public class TestHashTable { public static void main(String[] args) {
// TODO Auto-generated method stub
Hashtable h=new Hashtable();
MyKey z = new MyKey("zhangsan",18);
h.put(z,new Integer(1));
h.put(new MyKey("wangwu",12),new Integer(2));
h.put(new MyKey("lisi",29),new Integer(3));


Enumeration e=h.keys();
while(e.hasMoreElements())
{
MyKey key=(MyKey)e.nextElement();
System.out.print(key.tostring()+"=");
System.out.println(h.get(key));
}

System.out.println(h.get(z));
System.out.println(h.get(new MyKey("lisi",29)));///有问题,取不出3,显示NULL,哪里错了? }
 
}
class MyKey {
private String name=null;
private int age=0;
MyKey(String name,int age){
this.name=name;
this.age=age;

}
     public boolean equals(Object obj)
       {
       if(obj instanceof MyKey)
        {   
         MyKey objTemp=(MyKey)obj;   
        if(name.equals(objTemp.name)&&age==objTemp.age)
        { 
        return true;
        }
        else
        {
        return false;
        }
        }
       else  
        return false;
        
       }
       
       public int hashcode()
       {
        return name.hashCode() +age;
       }
       public String tostring()
       {
        return(new String(name+","+age));
       
       }

}
MyKey覆盖了equals和hashcode两个方法

解决方案 »

  1.   

    public int hashcode()
    改成 public int hashCode()
    注意方法名称另外,建议用HashMap代替HashTable
      

  2.   

    System.out.println(h.get(new MyKey("lisi",29)));///有问题,取不出3,显示NULL,哪里错了?
                             ~~~~
    要在实例吗?
      

  3.   

    哦,1楼是对的
    这边为什么还要NEW啊
      

  4.   

    1楼的believefym解决了此问题 谢谢啊
    原来只差了个大小写 我晕