我正在创建一个LinkedList类和一个LinkedListNode,我希望它们是通用的,以便我可以根据情况稍后选择类型参数。 所以我创建了这两个类:
DoublyLinkedList类:
public class DoublyLinkedList<T> {
// sentinel before first item
private NodeDoublyLinked<T> head;
// sentinel after last item
private NodeDoublyLinked<T> tail;
//number of elements
private int size;
// getter and setter methods here
//add new node to the linked List
public void addNode(T data){
NodeDoublyLinked<T> prev = tail.getPrev();
NodeDoublyLinked<T> node = new NodeDoublyLinked(data, prev, tail);
tail.setPrev(node);
size++;
}
}
和NodeDoublyLinked类:
import java.util.Iterator;
import java.util.NoSuchElementException;
public class NodeDoublyLinked<T> implements Iterable<T> {
private T data;
private NodeDoublyLinked<T> prev;
private NodeDoublyLinked<T> next;
public NodeDoublyLinked(T value, NodeDoublyLinked<T> previousN, NodeDoublyLinked<T> nextN) {
this.data = value;
this.prev = previousN;
this.next = nextN;
}
// getter and setter methods
@Override
public Iterator<T> iterator() {
return new NodeDoublyLinkedIterator();
}
private class NodeDoublyLinkedIterator implements Iterator<T> {
// the current node returned by next()
NodeDoublyLinked<T> current = prev.next;
@Override
public boolean hasNext() {
return current != null;
}
@Override
public T next() {
// code here
}
public void remove(){
// code here
}
}
}
在DoublyLinkedList类的addNode方法中,在这一行:
NodeDoublyLinked<T> node = new NodeDoublyLinked(data, prev, tail);
我收到警告:
NodeDoublyLinked是一种原始类型。对泛型类型的引用 NodeDoublyLinked应该参数化
我检查了documentation of generics和type inference,所以我知道我应该在右侧分配一个类型参数,但它也不正确。我应该用类型参数替换类型参数,例如Integer吗? NodeDoublyLinked的构造函数有什么问题吗?