[英]Dequeueing from a generic type queue, null pointer exception?
I am trying to make it dequeue the front node and print it out, however I am getting the following error: 我正在尝试使其退出前端节点并打印出来,但是出现以下错误:
Exception in thread "main" java.lang.NullPointerException
线程“主”中的异常java.lang.NullPointerException
at MyQueue.toString(MyQueue.java:25)在MyQueue.toString(MyQueue.java:25)
at TestQueue.main(TestQueue.java:13)在TestQueue.main(TestQueue.java:13)
From the TestQueue
class, I am expecting the outputs 1 then after dequeueing 1 again, then finally 2 from the second toString
call. 在
TestQueue
类中,我期望输出1,然后再次使1出队,然后从第二个toString
调用最终2。
public class TestQueue {
public static void main(String[] args) {
MyQueue<String> qStr = new MyQueue();
qStr.enqueue("1");
qStr.enqueue("2");
qStr.enqueue("3");
qStr.enqueue("4");
qStr.enqueue("5");
qStr.toString(qStr.front);
qStr.dequeue();
qStr.toString(qStr.front);
}
}
public class MyQueue<T>{
MyNode<T> back;
MyNode<T> front;
public MyQueue(){
back = null;
front = null;
}
public void enqueue(T payload) {
if(back == null) {
MyNode<T> firstnode = new MyNode<T>(payload);
back = firstnode;
front = firstnode;
}
else {
MyNode<T> addtoback = new MyNode<T>(payload, back.next, null);
back = addtoback;
}
}
public String toString(MyNode<T> x) {
System.out.println(x.payload);
if(x.payload == null) {
return "";
}
else{
return (String) x.payload;
}
}
public void dequeue() {
if (isEmpty()) {
throw new RuntimeException("Queue underflow");
} else if (front == back) {
T payload1 = front.payload;
front = null;
back = null;
System.out.println(payload1);
}
T payload1 = front.payload;
front = front.previous;
System.out.println(payload1);
}
public Boolean isEmpty() {
if(back==null) {
return true;
}
return false;
}
public int size() {
MyNode<T> k = back;
if(isEmpty()||k.next==null) {
return 0;
}
k = k.next;
return 1+size();
}
You never set the previous
variable in the MyNode
class. 您永远不会在
MyNode
类中设置上previous
变量。
What is happening is that you set the front
variable in the MyQueue
class when you call enqueue(T)
for the first time. 发生的情况是,当您第一次调用
enqueue(T)
时,在MyQueue
类中设置了front
变量。 Once you call dequeue()
for the first time it sets the front
variable in the MyQueue
to the previous
variable in the MyNode
class which is never set. 第一次调用
dequeue()
时,它MyQueue
的front
变量设置为MyNode
类中从未设置的previous
变量。 front
in the MyQueue
class becomes null and the next time toString(MyNode<T>)
is called you get a NullPointerException
. front
在MyQueue
类成为空,下一次toString(MyNode<T>)
被称为你会得到一个NullPointerException
。
That is also why the first call to toString(MyNode<T>)
doesn't give a NullPointerException
. 这就是为什么第一次调用
toString(MyNode<T>)
不会给出NullPointerException
。 dequeue()
wasn't called yet. dequeue()
尚未被调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.