mar*_*ary 3 java generics iterator
我有以下设计:我有一个抽象类Instance,我有一个Library扩展的类,Instance我有一个File也扩展了实例的类
我已经创建了自己的链表实现,它的定义如下:
public class List<T extends Instance> implements Iterable {
//some other code here
public Iterator iterator(){
return new ListIterator(this);
}
Run Code Online (Sandbox Code Playgroud)
现在我创建了一个类
public class ListIterator<T extends Instance> implements Iterator<T> {
private List thisList;
private Node current;
public ListIterator(List l){
thisList=l;
current=thisList.head.next;
}
@Override
public boolean hasNext() {
if(current==null)
return false;
return false;
}
@Override
public T next() {
Node temp=current;
current=current.next;
return temp.data;
}
}
Run Code Online (Sandbox Code Playgroud)
哪里Node是
public class Node<T extends Instance> {
public Node<T> next;
public Node<T> prev;
public T data;
public Node(T data,Node prev, Node next){
this.data=data;
this.prev=prev;
this.next=next;
}
}
Run Code Online (Sandbox Code Playgroud)
所以我的问题如下:返回 temp.data 的行出现错误:
类型不匹配 - 无法从实例转换为 T。
这段代码有什么问题?
我会说这Node.data是对Instance对象的引用?如果是这种情况,编译器无法自动将 an 更改Instance为 a T,因为即使T是Instance对象 ( T extends Instance),任何给定的Instance也可能不是 a T。
Java泛型教程解释了它:http : //docs.oracle.com/javase/tutorial/extra/generics/subtype.html
此外,在您的List<T>类中,您应该使用and将Iteratorand指定ListIterator为泛型,否则编译器将无法正确处理泛型。您的参考也需要是通用的:Iterator<T>ListIterator<T>NodeNode<T>
因此你应该使用
private Node<T> current;
Run Code Online (Sandbox Code Playgroud)
和
public T next() {
Node<T> temp=current;
current=current.next;
return temp.data;
}
Run Code Online (Sandbox Code Playgroud)
当您将原始类型用于泛型类时,编译器通常会警告您。