[英]An instantiable Java generic for <E extends Comparable<E>>
[英]Java Generics E extends Comparable<E> leaves warning
我正在嘗試創建一個Generic類,其中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>
隱藏了來自LinkedList<E extends Comparable<E>>
的E
LinkedList<E extends Comparable<E>>
。 此警告應顯示在此處:
private class Node<E extends Comparable<E>> {
^ here you should get a warning with the message
The type parameter E is hiding the type E
}
由於Node
是一個內部類,因此它可以直接訪問LinkedList
聲明的泛型E
這意味着,您可以輕松聲明沒有泛型類型的Node
類:
private class Node {
E data;
Node next;
//rest of code...
}
然后,您可以在類中輕松使用Node node
變量。
請注意,如果將Node
聲明為靜態類,則通用是必需的,然后您不應聲明原始變量。 這將是:
private static Node<E extends Comparable<E>> {
E data;
Node<E> next;
//rest of code...
}
private Node<E> head;
凡E
中使用static class Node
是從不同E
通用在聲明LinkedList
。
private Node head;
這段代碼正在拋出警告。 Node在聲明時希望有一個類型。 防爆。
private Node<something> head;
您沒有指定任何內容,因此警告您沒有指定類型。
在您的情況下,您可能想要:
private Node<E> head;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.