Java泛型扩展了Comparable<;E>;留下警告
我试图创建一个泛型类,其中Java泛型扩展了Comparable<;E>;留下警告,java,generics,Java,Generics,我试图创建一个泛型类,其中E扩展了可比较的E,但我在Eclipse中得到一个警告,它说: 节点是原始类型。对泛型类型LinkedList E的引用。应参数化节点E 代码如下: public class LinkedList<E extends Comparable<E>> { // reference to the head node. private Node head; private int listCount; // Lin
E扩展了可比较的E
,但我在Eclipse中得到一个警告,它说:
节点是原始类型。对泛型类型LinkedList E的引用。应参数化节点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;
}
}
}
公共类链接列表
{
//对头部节点的引用。
专用节点头;
私有整数列表计数;
//链接列表构造函数
公共空白添加(E数据)
//post:将指定的元素追加到此列表的末尾。
{
节点温度=新节点(数据);
节点电流=头;
//从head节点开始,爬网到列表的末尾
while(current.getNext()!=null)
{
current=current.getNext();
}
//最后一个节点的“下一个”引用设置为新节点
当前设置下一步(温度);
listCount++;//增加变量的元素数
}
私有类节点
{
//引用链中的下一个节点,
节点下一步;
//此节点携带的数据。
//可以是您需要的任何类型。
E数据;
//节点构造函数
公共节点(E_数据)
{
next=null;
数据=_数据;
}
//另一个节点构造函数,如果我们想
//指定要指向的节点。
公共节点(E_数据,节点_下一步)
{
下一步=_下一步;
数据=_数据;
}
//这些方法应该是不言自明的
公共E getData()
{
返回数据;
}
公共无效设置数据(E_数据)
{
数据=_数据;
}
公共节点getNext()
{
下一步返回;
}
公共void setNext(节点_next)
{
下一步=_下一步;
}
}
}
这段代码正在抛出警告。节点在声明时需要有一个类型。前
private Node<something> head;
私有节点头;
您没有指定任何内容,因此它警告您尚未指定类型
在您的情况下,您可能需要:
private Node<E> head;
私有节点头;
这里的主要问题是节点中的generic
将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
}
然后,您可以在类中轻松地使用节点
变量
请注意,如果将节点
声明为静态类,则必须使用泛型,然后不应声明原始变量。这将是:
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
中声明的E
泛型不同,则在此处使用时应将节点
参数化(带E):专用节点头
@LuiggiMendoza Okay:(叹气,我只是以正确的方式使用了否决票:这个答案没有用。如果你认为我的答案没有用,就否决我,我不会生气:)。你太认真了。
private class Node {
E data;
Node next;
//rest of code...
}
private static Node<E extends Comparable<E>> {
E data;
Node<E> next;
//rest of code...
}
private Node<E> head;