Java中Stack的push()方法中的NullPointerException

时间:2011-08-21 14:46:39

标签: java stack nullpointerexception

如何在Java的堆栈中将NullPointerException合并到以下push()方法中?

public void push(E e) {
        int len = size();
        if (len == 0)
            throw new NullPointerException();
        else
            addElement(e);
        System.out.println("The element pushed is " + e);
    }

在PSVM中,每当我调用push()方法时,它都会在不添加到堆栈的情况下发出NullPointerException。

public static void main(String[] args) {
        try {
            SortableStack<Object> s = new SortableStack<Object>();
            s.push(10);
            s.push(20);
            System.out.println("The element popped is " + s.pop());
        } 
        catch (NullPointerException e) {
            System.out.println("Null Pointer Exception encountered!");
        }
}

2 个答案:

答案 0 :(得分:1)

我不确定你想要实现的目标,但你应该检查null的{​​{1}} - 而不是堆栈的大小:

e

答案 1 :(得分:0)

嗯,我想这是因为当你创建对象时,它的初始大小为零。当你拨打push时,它会检查(if len == 0)的大小,发现它为零,所以会抛出一个npe!