我不知道为什么我不能做一些简单的事情,比如将泛型对象推送到堆栈上。我决定我需要一些帮助来弄清楚这件事。这就是我所拥有的:
private void preOrderTrav(BSTnode<K> node) {
if(node != null){
myStack.push(node); //Null pointer exception
while(!myStack.isEmpty()){
myStack.pop();
node = node.getLeft();
myStack.push(node.getRight());
myStack.push(node.getLeft());
}
}
}这是从我的构造函数中调用的:
public BSTSortedListIterator(BSTnode<K> root) {
preOrderTrav(root);
}有谁有什么想法吗?顺便说一句,我得到了这个错误:
Exception in thread "main" java.lang.NullPointerException
at BSTSortedListIterator.preOrderTrav(BSTSortedListIterator.java:33)
at BSTSortedListIterator.preOrderTrav(BSTSortedListIterator.java:31)
at BSTSortedListIterator.<init>(BSTSortedListIterator.java:43)
at BSTSortedList.iterator(BSTSortedList.java:130)
at WebDictionary.main(WebDictionary.java:135)发布于 2013-04-25 16:24:51
如果您确定这就是获取NullPointerException的地方
myStack.push(node); 就像你提到的,有一张支票
if(node != null)唯一可以为空的是myStack。否则这是不完整的信息。
Exception in thread "main" java.lang.NullPointerException
at BSTSortedListIterator.preOrderTrav(BSTSortedListIterator.java:33)这是BSTSortedListIterator.java中的第33行myStack.push(node);吗
发布于 2013-04-25 16:25:49
在大多数情况下,myStack实例是空的,因为即使在插入空元素的情况下,stack.push也不会抛出错误。Java Stack classes使用Vector (或数组)作为底层存储,它在添加元素时将元素添加到其数组中:
elementData[elementCount++] = obj;所以,我不认为NPE是一种应有的推式方法。
发布于 2013-04-25 16:26:24
在调用preOrderTrav(node)之前,您需要在main或其他地方初始化myStack对象。如果没有像这样的线
myStack = new Stack<K>()那么很有可能,你忘记了这一点。
https://stackoverflow.com/questions/16209719
复制相似问题