【发布时间】:2014-12-08 12:28:17
【问题描述】:
我正在尝试创建一个通用类,E extends Comparable E 但我在 Eclipse 中收到一条警告:
LinkedList.Node 是一个原始类型。对泛型 LinkedList E .Node E 的引用应该被参数化
代码如下:
public class LinkedList<E extends Comparable<E>>
{
// reference to the head node.
private Node head;
private int listCount;
// LinkedList constructor
public void add(E data)
// post: appends the specified element to the end of this list.
{
Node temp = new Node(data);
Node current = head;
// starting at the head node, crawl to the end of the list
while(current.getNext() != null)
{
current = current.getNext();
}
// the last node's "next" reference set to our new node
current.setNext(temp);
listCount++;// increment the number of elements variable
}
private class Node<E extends Comparable<E>>
{
// reference to the next node in the chain,
Node next;
// data carried by this node.
// could be of any type you need.
E data;
// Node constructor
public Node(E _data)
{
next = null;
data = _data;
}
// another Node constructor if we want to
// specify the node to point to.
public Node(E _data, Node _next)
{
next = _next;
data = _data;
}
// these methods should be self-explanatory
public E getData()
{
return data;
}
public void setData(E _data)
{
data = _data;
}
public Node getNext()
{
return next;
}
public void setNext(Node _next)
{
next = _next;
}
}
}
【问题讨论】:
-
Node在使用时应参数化(使用 E),如下所示:private Node head; -
@LuiggiMendoza 好的 :( Please read this to understand raw types.