我正在为一个链表类的Iterator工作。我正在将节点分配给内部类中的变量,并且出现“类型不匹配”错误。相关代码如下。
public class RegLinkList<T> implements Iterable<T>{
private Node<T> head;
public RegLinkList() {
head = null;
}
public class Node<T> {
public Node<T> next = null;
public T data = null;
Node(T data){
this.data = data;
}
}
public class ListIterator<T> implements Iterator<T>{
Node<T> current = head;
Node<T> previous = head;
我明白了:
Type mismatch: cannot convert from
RegLinkList<T>.Node<T> to RegLinkList<T>.Node<T>
编辑:我目前的解决方案是未经检查的演员阵容
public class ListIterator<T> implements Iterator<T>{
Node<T> current = (Node<T>) head;
Node<T> previous = (Node<T>) head;
你得到这个错误的原因是编译器做你说的而不是你的意思。 T
的ListIterator
和T
的RegLinkList
被视为两种不同的类型。如果您使用例如,将会更清楚U
而不是T
。
您的问题的解决方案可能是使类静态并将head
元素传递给构造函数。这样你仍然声明不同的T
s但是因为你传递了原始元素(并因此“告诉”编译器一个T
与另一个相同),它会很高兴。以下代码很高兴编译(我添加了缺少方法实现,没有功能):
import java.util.Iterator;
public class RegLinkList<T> implements Iterable<T> {
private Node<T> head;
public RegLinkList() {
head = null;
}
public static class Node<T> {
public Node<T> next = null;
public T data = null;
Node(T data) {
this.data = data;
}
}
public static class ListIterator<T> implements Iterator<T> {
Node<T> current;
Node<T> previous;
public ListIterator(Node<T> head) {
current = head;
previous = head;
}
@Override
public boolean hasNext() {
return false;
}
@Override
public T next() {
return null;
}
}
@Override
public Iterator<T> iterator() {
return new ListIterator<T>(head);
}
}