通用推送到堆栈会产生编译错误

时间:2017-05-11 06:27:54

标签: java generics

我有一个Node类定义如下 -

public static class Node<T> {
    public T value;
    public Node<T> left;
    public Node<T> right;

    public Node(T value) {
        this.value = value;
        left = null;
        right = null;
    }

}

现在我正在尝试将Node<Integer>添加/推送到Stack<Node<T>>,这会给我一个编译错误。

private static <T> Node<T> createTree(Expression expression) {
    Stack<Node<T>> nodeStack = new Stack<>();
    Stack<Token> tokenStack = new Stack<>();

    Token token = getNextToken(expression);

    while (token != null) {
        if (token instanceof OpenParenthesis) {
            tokenStack.push(token);
        } else if (token instanceof Element) {
            nodeStack.push(new Node<Integer>(((Element) token).value)); // Here
        } else if (token instanceof EmptyElement) {
            nodeStack.push(null);
        } else if (token instanceof CloseParenthesis) {
            if (nodeStack.size() == 1) {
                tokenStack.pop();
                return nodeStack.pop();
            }

            tokenStack.pop();
            Node<T> right = nodeStack.pop();
            Node<T> left = nodeStack.pop();
            Node<T> node = nodeStack.pop();
            node.left = left;
            node.right = right;
            nodeStack.push(node);
        }

        token = getNextToken(expression);
    }

    return null;
}

这一行没有编译 -

nodeStack.push(new Node<Integer>(((Element) token).value));

带消息 -

  push(Node<T>)中的

Stack无法应用于(Node<java.lang.Integer>)

1 个答案:

答案 0 :(得分:1)

<T>类型参数是方法级参数。即你在方法签名处定义了它:

private static <T> Node<T> createTree(Expression expression

您的节点堆栈具有相同的类型:

Stack<Node<T>> nodeStack = new Stack<>();

因此,当您进入该堆栈时,您需要相同类型的令牌:

nodeStack.push(new Node<T>(((Element) token).value));
//                   ^^^^^^ - using <T>

那么,你如何让它适合你呢?如果您确定所有推送到nodeStack的内容都是nullNode<Integer> - 这就是它的样子 - 那么您可以摆脱方法级类型令牌:

private static Node<Integer> createTree(Expression expression) {
    Stack<Node<Integer>> nodeStack = new Stack<>();
    // ...
    } else if (token instanceof Element) {
         nodeStack.push(new Node<Integer>(((Element) token).value)); // Here
    }
    // ...
            Node<Integer> right = nodeStack.pop();
            Node<Integer> left = nodeStack.pop();
            Node<Integer> node = nodeStack.pop();
    // ...
    }
}