尝试迭代列表时抛出 Java ClassCastException

标签 java classcastexception

我的代码在运行时失败并出现 ClassCastException。我尝试过调试但没有成功。我已经声明了一个带有字段的类主题,并尝试将该类的对象加载到列表中。下面是代码。它在以下行失败:List items = (List)(it.next())。为泛型添加 ? 没有帮助。我猜想该对象已被强制转换,尽管 List 声明中没有提到泛型。我在这里缺少一个基本概念吗?

在下面的方法中,我尝试将数据编码到 xml 文件中。

 private void encodeSection(PrintStream output, Indenter indenter,
                                   String name, List list) {
            String indent = indenter.makeString();

            output.println(indent + "<" + name + "s>");

            indenter.in();
            String indentNext = indenter.makeString();

            if (list == null) {
                // the match is any
                output.println(indentNext + "<Any" + name + "/>");
            } else {
                String nextIndent = indenter.makeString();

                Iterator it = list.iterator();
                indenter.in();

                while (it.hasNext()) {
                  List items = (List)(it.next());//-------------> Error occurs
                    output.println(indentNext + "<" + name + ">");

                    Iterator matchIterator = items.iterator();
                    while (matchIterator.hasNext()) {
                        TargetMatch tm = (TargetMatch)(matchIterator.next());
                        tm.encode(output, indenter);
                    }

                    output.println(indentNext + "</" + name + ">");
                }

                indenter.out();
            }

            indenter.out();
            output.println(indent + "</" + name + "s>");
        }

    }

堆栈跟踪:

Exception in thread "main" java.lang.ClassCastException: SubjectID_V cannot be cast to java.util.List
    at Target_V.encodeSection(Target_V.java:71)
    at Target_V.encode(Target_V.java:41)
at com.sun.xacml.AbstractPolicy.encodeCommonElements(Unknown Source)
    at com.sun.xacml.PolicySet.encode(Unknown Source)
    at PolicyFactory_V.main(PolicyFactory_V.java:56)

最佳答案

List items = (List)(it.next()) 仅当您要迭代的 List 仅包含 List< 类型的元素时才有效 (即实现 List 接口(interface)的类的实例)。

根据您收到的错误,您正在尝试将 SubjectID_V 类型的实例转换为 List。您应该查看初始化该列表的代码。您的错误可能就在那里。

使用通用列表可能会帮助您避免此异常,因为它首先会阻止代码通过编译。

关于尝试迭代列表时抛出 Java ClassCastException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26777582/

相关文章:

java - 如何触发 MINA 客户端消息事件?

java tcp 消息传递不起作用,但 .net 版本可以

java - ClassCastException 从数据库中的组合框中插入数据

java - 通用数组复制的问题

Java.swing.ComboBox 不能在 Button classException 上转换

java - 如何告诉 Jersey Jackson 不要序列化一项资源?

java - hibernate/JPA : Mapping entities to different databases

java - 如何在 Java Applet 中即时显示图像?

java - 下一个代码中类转换异常的确切原因是什么?

java - java.lang.Object 的泛型不能转换为 [Ljava.lang.Object