[英]weird typing error with private iterator in generic class
I'm implementing a linked list in Java 1.7 and I don't understand this behaviour. 我正在Java 1.7中实现一个链表,但我不理解这种行为。 The parts of the code that matter are this:
重要的代码部分是这样的:
public class LListSent<T> implements Iterable<T>{
//...
public T get(int pos) {
//...
}
//...
private class LListSentIterator {
private final LListSent list;
private int currPos;
private LListSentIterator(LListSent list) {
this.list = list;
currPos = 0;
}
//...
@Override
public T next() {
return list.get(currPos++); //exception in this line
}
}
}
The exception I get is: 我得到的异常是:
incompatible Type: Object cannot be converted to T
where T is a type-variable:
T extends Object declared in class LListSent
eve though left.get return a T
object. 前夕,尽管left.get返回一个
T
对象。 Why does this happen? 为什么会这样?
Your list
variable is of type LListSent
which is the raw type (so not parametrized) as such the get method called on this instance will return Object
and not T
. 您的
list
变量的类型为LListSent
,这是原始类型(因此未参数化),因此在此实例上调用的get方法将返回Object
而不是T
Change the type of your variable to LListSent<T>
. 将变量的类型更改为
LListSent<T>
。
Note that this will work because LListSentIterator
is an inner class and has access to the type variable T
. 请注意,这将起作用,因为
LListSentIterator
是一个内部类,并且可以访问类型变量T
A cleaner solution would be to parametrized your LListSentIterator
class with a type parameter S
and so your list
variable would become of type : LListSent<S>
较干净的解决方案是使用类型参数
S
参数化您的LListSentIterator
类,因此您的list
变量将变为类型: LListSent<S>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.