我需要使用泛型实现自定义链表。如何让我的自定义链表使用泛型?
这里是我做了什么
public class Node {
Node next;
Object data;
public Node(Object data) {
next = null;
this.data = data;
}
public Object getData() {
return data;
}
public void setData(Object dataValue) {
data = dataValue;
}
public Node getNext() {
return next;
}
public void setNext(Node nextValue) {
next = nextValue;
}
}
public class LinkedList {
private Node head;
private int size;
public LinkedList() {
head = new Node(null);
size = 0;
}
public void add(Object data) {
Node node = new Node(data);
Node current = head;
while (current.getNext() != null) {
current = current.getNext();
}
current.setNext(node);
size++;
}
public int getSize() {
return size;
}
public String toString() {
Node current = head.getNext();
String elements = "";
while (current != null) {
elements += "[" + current.getData().toString() + "]";
current = current.getNext();
}
return elements;
}
}
public class Main {
public static void main(String[] args) {
System.out.println("Hello there!");
LinkedList list = new LinkedList();
list.add("First node");
list.add("Second node");
list.add("Third node");
list.add("Fourth node");
list.add("Fifth node");
System.out.println("Linked list contains " + list.getSize() + " nodes");
System.out.println("Here they are: " + list);
}
}
我不知道,或者只是不明白,我应该使用泛型和如何?有任何想法吗?
为什么不使用java LinkedList类型? –
@GuillaumeS看起来像功课 –
Luiggi,猜对了 – user3127896