簡體   English   中英

Java中的通用鏈接列表

[英]Generic Linked List in java

我正在學習泛型,並想創建一個泛型鏈表。

但是我正在遵循編譯時錯誤。

 Type mismatch: cannot convert from LinkedList<E>.Node<E> to LinkedList<E>.Node<E> 
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();
    }
}

請讓我知道為什么我收到此錯誤?

E here private class Node<E> {在此處隱藏Epublic class LinkedList<E> {

Node類不需要是泛型的。 它包含一個泛型字段value ,該value取決於LinkedListE泛型。 夠了

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();
    }
}

編輯

你能告訴我編譯器在拋出錯誤消息時要說些什么嗎

當你寫:

 this.next = head;

您必須注意,這兩個變量不依賴同一類型。

  • next是以此方式在Node<E>類中聲明的字段: Node<E> next

  • head是以這種方式在LinkedList<E>類中聲明的字段: Node<E> head

但是,編譯器不會將Node<E>類中聲明的E類型視為與LinkedList<E>類中聲明的E類型相同, 因為這是兩個不同的類型聲明

所以在這里 :

this.next = head;

編譯器無法從LinkedList<E>.Node<E>分配給LinkedList<E>.Node<E>因為Node<E>類的Node<E> next字段和LinkedList<E>Node<E> head字段LinkedList<E>類不聲明相同的類型(也不能轉換)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM