Java 更改指针时引发NullPointerException
我必须在LinkedList类中实现一个Java 更改指针时引发NullPointerException,java,nullpointerexception,linked-list,Java,Nullpointerexception,Linked List,我必须在LinkedList类中实现一个undo()方法。每次通过add()添加任何元素时,都会将该元素推入undoStack。现在,我有6个元素,代码从这一行抛出一个NullPointerException: object.prev.next = object.next; 有人能告诉我如何解决这个问题吗 protected Node<T> beginMarker; // Dummy node marking the front of the list protected No
undo()
方法。每次通过add()
添加任何元素时,都会将该元素推入undoStack
。现在,我有6个元素,代码从这一行抛出一个NullPointerException
:
object.prev.next = object.next;
有人能告诉我如何解决这个问题吗
protected Node<T> beginMarker; // Dummy node marking the front of the list
protected Node<T> endMarker; // Dummy node marking the back of the list
//beginMarker and endMarker are already initialized!
public void undo() {
if(undoStack.isEmpty()) {
throw new RuntimeException("Undo history is empty");
} else {
Node<T> object = undoStack.topAndPop();
redoStack.push(object);
if(object == beginMarker) {
beginMarker = beginMarker.next;
} else {
object.prev.next = object.next;
}
if(object == endMarker) {
endMarker = object.prev;
} else {
object.next.prev = object.prev;
}
}
}
受保护节点beginMarker;//标记列表前面的虚拟节点
受保护的节点结束标记;//标记列表后面的虚拟节点
//beginMarker和endMarker已初始化!
公共作废撤消(){
if(undoStack.isEmpty()){
抛出新的RuntimeException(“撤消历史记录为空”);
}否则{
节点对象=undoStack.topAndPop();
redoStack.push(对象);
if(object==beginMarker){
beginMarker=beginMarker.next;
}否则{
object.prev.next=object.next;
}
if(object==endMarker){
endMarker=object.prev;
}否则{
object.next.prev=object.prev;
}
}
}
代码太少,无法调试,添加对象时是否未正确设置prev
或next
属性?调试以查看null
的内容。我把我的钱赌在object.prev上。我猜你遇到了object是最后一个元素的情况,object.next是null,为什么要调用object.next抛出一个NullPointerException
如果object.next
是null,但是object
不是吗?@Manu你说得对,在该行中,object
或object.prev
为空。