gpt4 book ai didi

java - java中的通用链表

转载 作者:行者123 更新时间:2023-11-29 07:30:21 24 4
gpt4 key购买 nike

我正在学习泛型,想创建一个泛型链表。

但是我遇到了以下编译时错误。

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

编辑

could you please tell me what compiler wants to say when it throw error message

当你写的时候:

 this.next = head;

你必须意识到这两个变量不依赖于相同的类型。

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

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

但是 ENode<E> 中声明的类型编译器认为类不相同 ELinkedList<E> 中声明的类型class 因为这是两个不同的类型声明

所以在这里:

this.next = head;

编译器无法从 LinkedList<E>.Node<E> 赋值至 LinkedList<E>.Node<E>因为Node<E> next来自 Node<E> 的字段类和 Node<E> head来自 LinkedList<E> 的字段类不声明相同类型(也不可转换)。

关于java - java中的通用链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43715584/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com