Reputation: 119
I am implementing a priority queue using a stack, but a NullPointerException
is occurring and I can't figure out why. I am trying to add an integer "1" by using the push method in the MyStack
class. The error occurs at the add statement.
class MyStack<E> {
private PriorityQueue<MyNode<E>> pq;
int p =0;
public void push(int j){
p++;
pq.add(new MyNode(j,p)); // error detected here
}
public MyNode pop(){
if(isEmpty()){
return null;
}
return pq.poll();
}
public boolean isEmpty() {
return pq.isEmpty();
}
}
Edited: Reflects problem encountered in a proper manner :)
Upvotes: 0
Views: 58
Reputation: 3456
Change your line private PriorityQueue<MyNode<E>> pq
//it is not initialized thats why NPE occurs.
to
private PriorityQueue<MyNode<E>> pq = new PriorityQueue<MyNode<E>>();
No need to have a ComparatorMyNode<E>
as a separate class. Instead of this, you can implements Comparable like MyNode<E> implements Comparable<E>
in your MyNode class and can override the
public int compareTo(E o) {
return 0;
}
method in your MyNode class.
Upvotes: 0
Reputation: 993
If the code is complete it is simple: The member pq of your class MyStack is never initialized.
Upvotes: 1