将变量分配给相同类型的对象时出现类型不匹配错误

Type mismatch error when assigning a variable to an object of the same type

我正在为链表开发迭代器 class。我正在将节点分配给内部 class 中的变量,并收到 "Type mismatch" 错误。相关代码如下。

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;

你得到这个错误的原因是编译器按照你说的去做,而不是按照你的意思去做。 ListIteratorTRegLinkListT 被视为两种不同的类型。如果您使用例如,它会变得更加清楚U 而不是 T.

您的问题的解决方案可能是使 类 静态并将 head 元素传递给构造函数。这样你仍然声明不同的 Ts 但因为你传递了原始元素(因此 "telling" 编译器认为一个 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);
    }
}