I am having trouble with java.util.LinkedList. I am getting a null pointer exception upon using the poll() on the list even after adding an element to the list. I am not using threads or anything similar to threads.
Any help is appreciated. Below is the myMethod code which is called from a main method of another class:
void myMethod(Node start, int startRow){
LinkedList<Node> queue = new LinkedList<Node>();
LinkedList<Integer> rowQueue = new LinkedList<Integer>();
queue.addFirst(start);
rowQueue.addFirst((Integer)startRow);
System.out.println( rowQueue.size() );
while (queue.size()!=0){
Node n = queue.poll();
int row = rowQueue.poll().intValue(); //This is the line 33 in the error!
/*Some remaining code which uses variables n and row. The thread of control does not reach here */
}
}
Below is the output:
Exception in thread "main" java.lang.NullPointerException
at BFS.isConnected(LinkedListTest.java:33)
at GraphsMain.main(GraphsMain.java:36)
1
ZERO
I am confused because the print statements execute after the error, and clearly I have written them the other way around. Is this a threading issue at all? I know that LinkedLists are not synchronized, but is that the problem here? should I be worried about it just for a simple implementation?
Assume that you’ve some elements to your queue and nothing in your rowQueue. Then your logic in the while loop would work as follows:
Node n = queue.poll();will get the first and only element from the queue and store in the n variable.It would check if the size of rowQueue is zero or not. If it is, it would print a zero
However, and your problem lies in here, it would still try to
poll()again, get a null this time and callintValue()on the returned value, resulting in the NullPointerExceptionThe issue as such lies with the following logic in your code:
While you’re checking if
rowQueue.size()is 0, and if true, you should not only print Zero but also ensure that you do not performint row = rowQueue.poll().intValue();. So you should consider breaking out of the loop or something along those lines.So you should try something like this: