日期:2014-05-20  浏览次数:20679 次

关与Hashtable类的问题
import   java.util.*;
public     class     MyKey
{
private   int   age;
private   String   name;


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)
{
if   (name.equals(obj.name)&&   age==obj.age)

return   true;

else  
return   false;
}
public   int   hashCode()
{
return   name.hashCode()+age;
}
public   static   void   main(String[]   args)  
{
Hashtable   numbers   =   new   Hashtable();

numbers.put(new   MyKey( "zhangshan ",18),new   Integer(1));
numbers.put(new   MyKey( "lisi ",12),new   Integer(2));
numbers.put(new   MyKey( "wangwi ",14),new   Integer(2));

Enumeration   e   =   numbers.keys();
while   (e.hasMoreElements())
{
MyKey   key   =   (MyKey)e.nextElement();

System.out.print(key.toString()+ "= ");

System.out.println(numbers.get(key).toString());
}

}
}
这个程序运行时为什么回找不到 name     age   变量呢..
请高手指教...

------解决方案--------------------
很明显啊

你的equals方法 有问题 要先转型

public boolean equals(Object obj) {
if (!(obj instanceof MyKey)) {
return false ;
}
MyKey mk = (MyKey) obj;
if (name.equals(mk.name) && age == mk.age)

return true;

else
return false;
}