I've been working for a couple of hours now trying to get an Stack based on an Array built and implemented. I have checked several sources and it looks like my ArrayStack class is constructed properly. However, when I run debug, 'head' stays null and size & sp go back to 0: therefore, nothing is actually getting pushed on the stack. Can someone help me understand what I have implemented incorrectly?
Here is my ArrayStack class:
public class ArrayStack <T>{
protected int sp; //empty stack
protected T[] head; //array
private int size;
@SuppressWarnings("unchecked")
public void stack(T t){
sp = -1;
size = 24; //sets the default size of the stack
head = (T[]) new Object [size];
}
public boolean isFull(){
return sp == -1;
}
public void push (T t){
if (!isFull())
head[++sp] = t;
}
public T pop (){
if (isFull()){
return null;
}
else
return head[sp--]; //LINE 30
}
}
Here is my Main Method:
public class StacksAndQsMain {
public static void main(String[] args) {
//Array Implementation
ArrayStack<String> as = new ArrayStack<String>();
String s = "Hello";
String s1 = "World";
String s2 = "Again";
as.push(s);
as.push(s1);
as.push(s2);
System.out.println (as.pop()); //LINE 15
System.out.println();
System.out.println (as.pop());
System.out.println();
System.out.println (as.pop());
System.out.println();
}
}
Lastly, here is my stack trace:
Exception in thread "main" java.lang.NullPointerException
at stackAndQs.ArrayStack.pop(ArrayStack.java:30)
at stackAndQs.StacksAndQsMain.main(StacksAndQsMain.java:15)
My variables at public void push (T t)
this ArrayStack<T> (id=17)
head null
size 0
sp 0
t "Hello" (id=18)