Java泛型捕获内部类
我有以下代码:Java泛型捕获内部类,java,inner-classes,nested-generics,Java,Inner Classes,Nested Generics,我有以下代码: public class UndirectedGraphImpl<N> { [...] public Iterator<Edge<N>> adj(N v) { return new AdjIterator(v); } private class AdjIterator implements Iterator<Edge<N>> { [...] }
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);
}
}
公共类UndirectedGraphImpl{
[...]
公共迭代器adj(nv){
返回新的adj迭代器(v);
}
私有类AdjIterator实现迭代器{
[...]
}
公共静态void main(字符串[]args){
图g=新的无向raphimpl();
[...]
迭代器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>
错误:不兼容的类型
迭代器it=g.adj(4);
^
必需:迭代器
发现:迭代器
其中CAP#1是一个新类型变量:
CAP#1从捕获的边缘延伸?延伸边缘
如果我用
Iterator<Edge<Integer>> it = (Iterator<Edge<Integer>>)g.adj(4);
Iterator it=(Iterator)g.adj(4);
然后我得到了一个未经检查的强制转换警告,但我不明白为什么编译器捕获了“?扩展边缘”。有人能给我解释一下发生了什么以及如何解决这个问题吗
编辑:这是由UndirectedGraphImpl类实现的图形接口
public interface Graph<N> extends Iterable<N> {
[...]
Iterator<? extends Edge<N>> adj(N v);
[...]
}
公共接口图扩展了Iterable{
[...]
迭代器问题是您正在返回类型Iterator方法是如何声明的?您指的是哪个方法?“adj”方法在您在g
上调用它的第一个代码段中,因此它必须是Graph
中的一个,并且它应该由UndirectedGraphImpl
实现/扩展,但它不在您的第一个代码段中。您也可以发布Graph类吗?对不起,您是对的。如果我将g声明为Graph I,它将被定义为迭代器必须使用迭代器,或者如果可能的话,将接口更改为更加一致。