简体   繁体   English

错误参数类型E隐藏类型E

[英]Error parameter type E is hiding the type E

I am creating a generic linked stack. 我正在创建一个通用的链接堆栈。 This error shows up when creating the new node shown next: 创建下面显示的新节点时,将显示此错误:

private class Node<E> {

What is wrong with my code that is causing this? 导致此问题的代码有什么问题?

public class LinkedStack<E> implements StackBehavior<E> {

    private class Node<E> {
        private E element;
        private Node<E> next;
        private Node(E element) {
            this.element = element;
            this.next = null;

        }
        private Node(E element, Node<E> next) {
            this.element = element;
            this.next = next;
        }
    }

    private Node<E> top = null;

    public void push(E item) {
        top = new Node<E>(item, top);
    }

    public E pop() {
        if (top == null) {
            throw new EmptyStackException("Pop error: Stack is empty.");
        }
        E item = top.element;
        top = top.next;
        return item;
    }

    public E peek() {
        if (top == null) {
            throw new EmptyStackException("Peek error: Stack is empty.");
        }
        return top.element;
    }

    public boolean isEmpty() {
        return (top == null);
    }

    public String toString() {
        Node<E> curr = top;
        String stringStack = "top";
        while (curr != null) {
            stringStack += " --> " + curr.element;
            curr = curr.next;
        }
        return stringStack;
    }
}

In this declaration 在此声明中

public class LinkedStack<E> implements StackBehavior<E> {

you are declaring a new type variable named E . 您正在声明一个名为E的新类型变量。

In this inner class declaration 在这个内部类声明中

private class Node<E> {

you are declaring a new type variable also called E . 您正在声明一个新的类型变量,也称为E Any use of Node.E inside Node hides the accessible type variable E declared in LinkedStack . Node内部对Node.E任何使用Node.E隐藏LinkedStack声明的可访问类型变量E

This is a warning, not an error, but consider changing names if you really need the type variable (but it doesn't seem like you do). 这是一个警告,而不是一个错误,但是如果您确实需要类型变量,则可以考虑更改名称(但似乎不行)。

The problem is that <E> in Node<E> is hiding the <E> from top class LinkedStack<E> . 的问题是<E>Node<E>被隐藏<E>从顶级LinkedStack<E> There are two solutions for this: 有两种解决方案:

  • Remove the <E> from the inner class. 从内部类中删除<E> Usage of E inside it will automatically refer to the generic E in top class. 在其中使用E将自动引用顶级中的通用E

  • Make it an inner static class. 使它成为内部static类。 This will make its generic E different from the E in top class. 这将使其通用E与顶级E中的E不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM