将变量分配给相同类型的对象时,键入不匹配错误

问题描述 投票:0回答:1

我正在为一个链表类的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;
java types casting mismatch
1个回答
0
投票

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

您的问题的解决方案可能是使类静态并将head元素传递给构造函数。这样你仍然声明不同的Ts但是因为你传递了原始元素(并因此“告诉”编译器一个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);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.