您好,我已经创建了一个名为GenLinkedList的泛型类(它是单链接的linkedList),但我对泛型的理解相当陌生,因此我的程序没有正确实现。
我的节点类如下所示:
public class Node<AnyType> {
public AnyType value;
public Node<AnyType> next;
public Node(AnyType value, Node<AnyType> next) {
this.value = value;
this.next = next;
}
public Node(AnyType value) {
this.value = value;
this.next = null;
}
}我的GenLinkedList类如下所示:
public class GenLinkedList<AnyType> {
private Node<AnyType> head;
private Node<AnyType> tail;
int size = 0;
public void addFront(AnyType value) {
if(head == null) {
head = new Node(value);
tail = head;
}
else
{
head = new Node(value,head);
}
size++;
}
}我的main看起来像这样:
public class Main {
public static void main(String[] args) {
GenLinkedList list = new GenLinkedList(); // try <int> didnt work! What am I do wrong?
for(int i = 0; i < 10; i++) {
list.addFront(i);
}
System.out.println(list);
}
}发布于 2020-09-15 07:59:18
int是一个基本类型,您需要包装器类型Integer。喜欢,
GenLinkedList<Integer> list = new GenLinkedList<>(); https://stackoverflow.com/questions/63893258
复制相似问题