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)请高人指教!

解决方案 »

  1.   

    KeyTest key =(KeyTest) num.nextElement();
    这一句有问题
    hashtabletest里面是KeyTest为key,Integer为value
    因此,num.nextElement()是代表的里面的value,即Integer类型,因此只能转换成Integer类型,而不是转换成KeyTest类型
      

  2.   

    我觉得你好像put的时候put反了,你应该这样==>ht.(new Integer(1),new KeyTest("zhangsan",18));
    看不明白你的key和你的value到底什么意思,如果你一定要用KeyTest做key,1,2,3做value
    估计就是楼上的说法了
    //////////////////////////////////////////////////////////
    public Enumeration<V> elements()返回此哈希表中的值的枚举//
    //////////////////////////////////////////////////////////
    这个函数返回的是value的枚举类型
    所以如果你想返回key的应该用
    public Enumeration<K> keys()返回此哈希表中的键的枚举。
    这个函数才是你想要的结果
      

  3.   

    谢谢你们的回复,其实我的意思是想让key和value对应输出。正如楼上所说,首先我在put的时候put反了,再者我没有搞清楚elements()返回此哈希表中的值,又新认识了keys()返回此哈希表中的键。现在问题已经差不多解决,谢谢各位。