首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

遇到个这样的有关问题“java.lang.ClassCastException: java.lang.Integer”

2011-11-25 
遇到个这样的问题“java.lang.ClassCastException: java.lang.Integer”importjava.util.*//main函数public

遇到个这样的问题“java.lang.ClassCastException: java.lang.Integer
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));


看不明白你的key和你的value到底什么意思,如果你一定要用KeyTest做key,1,2,3做value
估计就是楼上的说法了
//////////////////////////////////////////////////////////
public Enumeration <V> elements()返回此哈希表中的值的枚举//
//////////////////////////////////////////////////////////
这个函数返回的是value的枚举类型
所以如果你想返回key的应该用
public Enumeration <K> keys()返回此哈希表中的键的枚举。
这个函数才是你想要的结果

热点排行