我有一个 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>)
inStack
cannot be applied to(Node<java.lang.Integer>)
最佳答案
<T>
类型参数是方法级别参数。 IE。您在方法签名中定义了它:
private static <T> Node<T> createTree(Expression expression
您的节点堆栈具有完全相同的类型:
Stack<Node<T>> nodeStack = new Stack<>();
因此,当您插入该堆栈时,您需要完全相同的类型 token :
nodeStack.push(new Node<T>(((Element) token).value));
// ^^^^^^ - using <T>
那么,如何让它为您服务呢?如果确定全部推送到nodeStack
将是null
和Node<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();
// ...
}
}
关于java - 通用推送到堆栈会出现编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43908015/