Java Generics E extends Comparable <E>留下警告

Nev*_*423 3 java generics

我正在尝试创建一个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;
        }
    }


}
Run Code Online (Sandbox Code Playgroud)

Lui*_*oza 7

这里的主要问题是<E>Node 中的泛型隐藏了Efrom 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
}
Run Code Online (Sandbox Code Playgroud)

由于Node是一个内部类,它可以直接访问E声明的泛型LinkedList.这意味着,您可以轻松地声明Node没有泛型类型的类:

private class Node {
    E data;
    Node next;
    //rest of code...
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以轻松地Node node在类中使用变量.


请注意,如果您声明Node为静态类,那么泛型将是必要的,然后您不应声明原始变量.这将是:

private static Node<E extends Comparable<E>> {
    E data;
    Node<E> next;
    //rest of code...
}

private Node<E> head;
Run Code Online (Sandbox Code Playgroud)

其中Eused in static class NodeE声明的泛型不同LinkedList.