import java.util.*;
//main 函数
public class HashTableTest {
public HashTableTest() {
}
public static void main(String[] args) {
HashTableTest hashtabletest = new HashTableTest();
Hashtable ht =new Hashtable();
ht.put(new KeyTest( "zhangsan ",18),new Integer(1));
ht.put(new KeyTest( "lisi ",20),new Integer(2));
ht.put(new KeyTest( "wangwu ",15),new Integer(3));
Enumeration num=ht.elements();
while(num.hasMoreElements())
{
KeyTest key =(KeyTest) num.nextElement();
System.out.print(key+ "= ");
System.out.println(ht.get(key));
}
}
}
//KeyTest
public class KeyTest {
public KeyTest(String name,int age) {
this.name=name;
this.age=age;
}
//override the equals method;
public boolean equals(Object obj){
if(obj instanceof KeyTest)
{
KeyTest kt=(KeyTest)obj;
if(name.equals(kt.name)&&age==kt.age)
{
return true;
}
else return false;
}
else
return false;
}
//override the hashCode method;
public int hashCode()
{
return name.hashCode()+age;
}
public String toString()
{
return this.name+ ", "+age;
}
private String name=null;
private int age=0;
}
出现的异常就是Exception in thread "main " java.lang.ClassCastException: java.lang.Integer
at HashTableTest.main(HashTableTest.java:29)
请高人指教!
------解决方案--------------------
KeyTest key =(KeyTest) num.nextElement();
这一句有问题
hashtabletest里面是KeyTest为key,Integer为value
因此,num.nextElement()是代表的里面的value,即Integer类型,因此只能转换成Integer类型,而不是转换成KeyTest类型
------解决方案--------------------
我觉得你好像put的时候put反了,你应该这样==> ht.(new Integer(1),new KeyTest( "zhangsan ",18));