你好,我已经创建了一个名为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++;
}
}
我的主要看起来像:
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);
}
}
int
是一个基元类型,您需要包装器类型Integer
。比如
GenLinkedList<Integer> list = new GenLinkedList<>();