I have to use a queue in an solitaire assignment, but I'm having some trouble using the linked list Queue class that I made. It won't take arrays at all.
class Testing {
public static void main (String [] args) {
Queue testlist = new Queue(); // testing
Queue [] testlistarray = new Queue [5000];
testlist.add("aa");
testlist.add("bb");
testlist.add("cc");
System.out.println(testlist.remove());
System.out.println(testlist.remove());
System.out.println(testlist.remove());
testlistarray[0].add("dd");
testlistarray[0].add("ee");
testlistarray[0].add("ff");
System.out.println(testlistarray[0].remove());
System.out.println(testlistarray[0].remove());
System.out.println(testlistarray[0].remove());
}
}
class Queue {
private int queuesize; // queue size
private Node first; // first in queue
private Node last; // last in queue
private class Node {
private Object data; // String, int, etc.
private Node next; // link to next
}
public Queue() { // create empty queue
first = null;
last = null;
}
public int size() { return queuesize; } // return current queue size
public boolean isempty() { return first == null; } // check if queue is empty
public void add(Object data) { // add object to queue
Node a = new Node();
a.data = data;
if (isempty()) { first = a; last = a;}
else { last.next = a; last = a;}
queuesize++;
}
public Object remove() { // remove earliest object in queue and return data
Object data = first.data;
first = first.next;
queuesize--;
return data;
}
}
It compiles just fine, but when running it I get:
aa
bb
cc
Exception in thread "main" java.lang.NullPointerException
at Testing.main(Testing.java:13)
I find it very strange, since testlist and testlistarray[] are essentially the same.
What am I doing wrong? I've been trying different things for over an hour, but I'm really just treading water at this point.
I'll try to look at it with a clear head in the morning. Hoping for some enlightening replies.
Thanks for reading :)