gpt4 book ai didi

java - Java 中的泛型在定义方法时抛出错误

转载 作者:行者123 更新时间:2023-11-29 08:20:51 25 4
gpt4 key购买 nike

我正在学习 Java 中的泛型。为此,我尝试了一个简单的 LinkedList。

class Node {
private int age;
private String name;
private Node next;

public Node(int age, String name) {
this.age = age;
this.name = name;
this.next = null;
}

public int getAge() {
return this.age;
}

public String getName() {
return this.name;
}

public Node getNext() {
return this.next;
}

public void setNext(Node next) {
this.next = next;
}
}

class LinkedList<T> {
private T head;
private T current;

public LinkedList() {
head = null;
current = null;
}

public void append(T x) {
if (head == null) {
head = x;
current = x;
}
else {
current.setNext(x);
current = x;
}
}

public T getAt(int index) {
T ptr = head;
for(int i = 0; i < index; i++) {
ptr = ptr.getNext();
}
return ptr;
}
}

class Main {
public static void main(String[] args) {
LinkedList<Node> list = new LinkedList<Node>();
list.append(new Node(39, "John"));
list.append(new Node(43, "Josh"));
Node x = list.getAt(1);
System.out.println(String.format("%d, %s", x.getAge(), x.getName()));
}
}

但是我得到了这个错误,而所有的方法都存在于 Node 类中。我做错了什么?

LinkedList.java:16: error: cannot find symbol
current.setNext(x);
^
symbol: method setNext(T)
location: variable current of type T
where T is a type-variable:
T extends Object declared in class LinkedList
LinkedList.java:24: error: cannot find symbol
ptr = ptr.getNext();
^
symbol: method getNext()
location: variable ptr of type T
where T is a type-variable:
T extends Object declared in class LinkedList
2 errors

最佳答案

如果current类型为 T , 你不能调用 Node 的方法setNext() 上的类(例如 current ) , 自 T当你实例化你的 LinkedList 时可以被任何类替代.

你的 Node类不应该是 LinkedList 的泛型类型参数. LinkedList应始终由 Node 组成秒。每个 Node 中存储的数据类型应该是泛型。

class Node<T> {
private T data;
private Node next;

public Node(T data) {
this.data = data;
this.next = null;
}
}

还有 LinkedList应包含 Node<T>节点:

class LinkedList<T> {
private Node<T> head;
private Node<T> current;
}

关于java - Java 中的泛型在定义方法时抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58705674/

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