NullPointerException in push() method of Stack in Java
How to I incorporate NullPointerException
in the following push()
method for a stack in Java?
public void push(E e) {
int len = size();
if (len == 0)
throw new NullP开发者_开发知识库ointerException();
else
addElement(e);
System.out.println("The element pushed is " + e);
}
In the PSVM, whenever I call the push()
method it gives out the NullPointerException without adding to the stack.
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!");
}
}
I am not %100 sure what you want to achieve, but you should check for null
-ness of e
, not the size of the stack:
public void push(E e) {
if (e == null) {
throw new NullPointerException("Can't push a null element");
}
addElement(e);
System.out.println("The element pushed is " + e);
}
Well I guess it is because when you create the object it's initial size is zero. And when you call push
it does that size check (if len == 0)
, finds it's zero so throws a npe!
精彩评论