java中的通用链接列表

Jok*_*ker 1 java generics linked-list

我正在学习泛型,并希望创建一个通用的链表.

但我得到了编译时错误.

Type mismatch: cannot convert from LinkedList<E>.Node<E> to
 LinkedList<E>.Node<E>
Run Code Online (Sandbox Code Playgroud)
public class LinkedList<E> {
    private Node<E> head = null;

    private class Node<E> {
        E value;
        Node<E> next;

        // Node constructor links the node as a new head
        Node(E value) {
            this.value = value;
            this.next = head;//Getting error here
            head = this;//Getting error here
        }
    }

    public void add(E e) {
        new Node<E>(e);
    }

    public void dump() {
        for (Node<E> n = head; n != null; n = n.next)
            System.out.print(n.value + " ");
    }

    public static void main(String[] args) {
        LinkedList<String> list = new LinkedList<String>();
        list.add("world");
        list.add("Hello");
        list.dump();
    }
}
Run Code Online (Sandbox Code Playgroud)

请让我知道为什么我收到此错误?

dav*_*xxx 5

E这里 private class Node<E> { 隐藏了E这里:public class LinkedList<E> {

Node课程不需要是泛型.它包含一个value依赖于E泛型的泛型字段LinkedList.这就够了.

public class LinkedList<E> {
    private Node head = null;

    private class Node {
        E value;
        Node next;

        // Node constructor links the node as a new head
        Node(E value) {
            this.value = value;
            this.next = head;//Getting error here
            head = this;//Getting error here
        }
    }

    public void add(E e) {
        new Node(e);
    }

    public void dump() {
        for (Node n = head; n != null; n = n.next)
            System.out.print(n.value + " ");
    }

    public static void main(String[] args) {
        LinkedList<String> list = new LinkedList<String>();
        list.add("world");
        list.add("Hello");
        list.dump();
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑

你能不能告诉我什么编译器在抛出错误信息时想说的话

当你写:

 this.next = head;
Run Code Online (Sandbox Code Playgroud)

你必须要知道这两个变量不依赖于相同的类型.

  • next是以Node<E>这种方式在类中声明的字段: Node<E> next

  • head是以LinkedList<E>这种方式在类中声明的字段: Node<E> head

E在声明的类型Node<E>类不会被编译为同一考虑E在声明的类型 LinkedList<E>,因为这是两个截然不同的类型声明.

所以在这里 :

this.next = head;
Run Code Online (Sandbox Code Playgroud)

编译器不能从分配LinkedList<E>.Node<E>LinkedList<E>.Node<E>因为Node<E> next从外地Node<E>类和Node<E> head从场LinkedList<E>类不声明相同的类型(和不可转换要么).