简体   繁体   中英

Why is a nullpointerexception occuring?

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 :)

如果代码完整,则很简单:永远不会初始化类MyStack的成员pq。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM