1

我有这个代码:

public class UndirectedGraphImpl<N> {
    [...]
    public Iterator<Edge<N>> adj(N v) {
        return new AdjIterator(v);
    }

    private class AdjIterator implements Iterator<Edge<N>> {
        [...]
    }

    public static void main(String[]args) {
        Graph<Integer> g = new UndirectedGraphImpl<Integer>();
        [...]
        Iterator<Edge<Integer>> it = g.adj(4);
    }

}

在编译时我得到这个错误:

error: incompatible types

        Iterator<Edge<Integer>> it = g.adj(4);
                                          ^
  required: Iterator<Edge<Integer>>
  found:    Iterator<CAP#1>
  where CAP#1 is a fresh type-variable:
    CAP#1 extends Edge<Integer> from capture of ? extends Edge<Integer>

如果我将该行替换为

Iterator<Edge<Integer>> it = (Iterator<Edge<Integer>>)g.adj(4);

然后我得到一个未经检查的强制转换警告,但我不明白为什么编译器会捕获“?扩展 Edge<Integer>”。有人向我解释它发生了什么以及如何解决这个问题?

编辑:这是由 UndirectedGraphImpl 类实现的 Graph 接口

public interface Graph<N> extends Iterable<N> {
    [...]
    Iterator<? extends Edge<N>> adj(N v);
    [...]
}
4

1 回答 1

2

The problem is that you're returning the type Iterator<? extends Edge<Integer>>, but you're trying to assign it to a variable of type Iterator<Edge<Integer>>.

The CAP thing you see comes from the process of capture conversion, which essentially tries to remove wildcards from returned types. But in this case they're still incompatible.

Capture conversion is defined in section 5.1.10 of the JLS in case you're interested in seeing the details.

于 2013-05-18T15:14:02.537 回答