gpt4 book ai didi

Java Generics E extends Comparable 留下警告

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:55:22 24 4
gpt4 key购买 nike

我正在尝试创建一个通用类,其中 E extends Comparable E 但我在 Eclipse 中收到一条警告:

LinkedList.Node is a raw type. References to generic type LinkedList E .Node E should be parameterized

代码如下:

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>在 Node 中隐藏了 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是一个内部类,它可以直接访问泛型 ELinkedList 中声明.这意味着,您可以轻松声明 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不同于 ELinkedList 中声明的通用.

关于Java Generics E extends Comparable<E> 留下警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26348488/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com