【问题标题】:for-each in Java trying to convert element typesJava中的for-each试图转换元素类型
【发布时间】:2014-07-21 05:35:50
【问题描述】:

在 ArrayList 上使用 for-each 构造时,我在 Java 中遇到问题。 在一个名为 Graph 的类中,我有受保护的属性

protected ArrayList<Edge<E>> edges

在我的 Edge 类中,我有受保护的属性

protected LinkedList<Connector<E>> pointers;

在我的 Edge 类中,我想要做的是定义一种方法来在屏幕上打印图表 g 的每个 Edge 的每个指针。我尝试使用不同的方法每次都会出错,然后我最终使用了 for-each 循环(我认为这是最好的选择,因为我知道我试图迭代的集合中元素的类型)。 我的代码如下:

public void printConnectors(Graph g){
    for (Edge<E> e: g.edges){
    System.out.println(e.iterator()); //I do have an iterator in my Edge class
    }
}

这不起作用,Eclipse 给了我以下错误:

类型不匹配:无法从元素类型 Object 转换为 Edge

我知道这可能是一个愚蠢的错误,源于我在代码中没有看到的东西,但我无法让它工作。谁能帮我解释一下为什么编译器会尝试从对象转换为边缘,即使边缘应该是边缘的 ArrayList?

【问题讨论】:

    标签: java eclipse arraylist foreach iterator


    【解决方案1】:

    您正在使用原始类型。代码应该是:

    public void printConnectors(Graph<E> g) { // use the generic type Graph<E> here,
                                              // not the raw type Graph
        for (Edge<E> e: g.edges) {
            System.out.println(e.iterator()); 
        }
    }
    

    What is a raw type and why shouldn't we use it?

    【讨论】:

    • ...对于那些想知道为什么会修复它的人,原始类型会剥离所有通用信息,有效(但不完全)将实例及其所有字段/方法视为它们的类型Object
    猜你喜欢
    • 1970-01-01
    • 2011-01-29
    • 1970-01-01
    • 2011-08-31
    • 1970-01-01
    • 1970-01-01
    • 2015-07-31
    • 2017-01-23
    • 2019-02-10
    相关资源
    最近更新 更多