简体   繁体   English

获取ClassCastException

[英]Getting ClassCastException

I am typecasting the object to a bean class ,which in turn gives me a exception ClassCastException,i am not getting the issue behind this. 我正在将该对象类型转换为Bean类,这反过来又给了我一个ClassCastException异常,我没有得到背后的问题。

 Hashtable listEvent = getEvents(label1.getText(), str);

  Enumeration events = listEvent.keys();
   while (events.hasMoreElements()) {
    String key = (String) events.nextElement();

    if (key.equals(label1.getText())) {

       Vector object = (Vector) listEvent.get(key);

       Enumeration hashtable = listEvent.keys();
        while (hashtable.hasMoreElements()) {
          String keys = (String) hashtable.nextElement();
           if (keys.equals(label1.getText())) {

  Vector data = (Vector) listEvent.get(keys);
       for (int i = 0; i < data.size(); i++) {
      EventsBean bean1 = (EventsBean) data.elementAt(i);

I get an error while the running the application for typecasting to EventsBean. 运行用于类型转换到EventsBean的应用程序时出现错误。

First of all, if you used generic collections rather than raw types ( Map<String, List<EventsBean>> instead of Hashtable ), those errors would be caught by the compiler. 首先,如果使用通用集合而不是原始类型( Map<String, List<EventsBean>>而不是Hashtable ),则编译器将捕获这些错误。

Forget about Vector, Hashtable and Enumeration. 忘记向量,哈希表和枚举。 They should not be used anymore since Java 1.2. 从Java 1.2开始,不应再使用它们。

And finally, why are you iterating on the hash table keys, instead of looking up the value directy? 最后,为什么要迭代哈希表键,而不是直接查找值?

Instead of 代替

Enumeration events = listEvent.keys();
while (events.hasMoreElements()) {
    String key = (String) events.nextElement();
    if (key.equals(label1.getText())) {
       Vector object = (Vector) listEvent.get(key);

Just use 只需使用

Vector object = (Vector) listEvent.get(label1.getText());

Now to answer your question: if you get a ClassCastException, it means that the objects stored in the collection are not what you think they are. 现在回答您的问题:如果收到ClassCastException,则意味着存储在集合中的对象不是您认为的那样。 Check the code which fills the collection. 检查填充集合的代码。 (and switch to generic, modern collections) (并转换为通用的现代收藏)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM