Reputation: 125
i'm currently working through generic classes and stacks. I've created a class with an arrayList and create methods for push, peek and pop.
Whenever I run the driver though I get an index of of bounds exception and i'm confused to why. Any help would be great:
GenericStack class
public class GenericStack <T> {
public ArrayList<T> stack = new ArrayList<T>();
private int top = 0;
public int size () {return top; };
public void push (T element){
stack.add(element);
top++;
}
public T pop() {
if (top == -1) {
return null; //means stack is empty
}
T val = stack.get(top);
stack.remove(top);
top--;
return val;
}
public T peek(){
if (top == -1){
return null;
}
T val = stack.get(top);
return val;
}
}
and my GenericDriver class
public class GenericDriver extends GenericStack {
public static void main (String [] args){
GenericStack<String> strings = new GenericStack<String>();
strings.push ( "hi");
strings.push ("how are you?");
strings.push ("Hi again");
strings.push ("One more");
if (strings.size() == 0) {
System.out.println("Stack is empty.");
} else {
System.out.println("Stack contains " + strings.size() + " items.");
{
System.out.println("top value: (using pop) " + strings.pop());
System.out.println("Stack now contains: " + strings.size() + " items");
System.out.println("The new top value, using peek: " + strings.peek());
}
}
If anyone could tell me why i'm getting this exception it'll be brilliant
Upvotes: 1
Views: 1134
Reputation: 300
On first push operation GenericStack.push("java") increases to "1". Then if we
perform GenericStack.pop(), we are trying to fetch from index '1' for which object is not initialized. Below code changes should work:-
private int top = -1;
public int size () {
return top;
}
public void push (T element){
top++;
stack.add(element);
}
Upvotes: 0
Reputation: 19776
The problem here is that you start top
as 0. When adding one item to the stack, you increment top. Now your top value is 1. But the index which you should use in pop()
should be 0, not 1, because the first index of an ArrayList
starts at 0.
Thus you should initialize your top
as -1 instead of 0. (which is what you also check for later to signal an empty stack).
Upvotes: 1
Reputation: 3396
Decrement top
previously to pop the element from the list.
top--;
T val = stack.get(top);
stack.remove(top);
Because top has the number of the elements, since the array is zero-based the index is always one less than the number of the elements.
Upvotes: 1
Reputation: 95958
Your stack looks like this:
"One more"
"Hi again"
"how are you?"
"hi"
Now top
is 4.
When you do pop
, you're trying to get the element at index 4
in the ArrayList, but arrays are zero-based in Java, there is no element 4, the elements are in the range [0-3]
You should initialize top
to -1 instead of 0 at the beginning, so when you'll try to get the "top" element, you won't get IndexOutOfBoundsException
.
Upvotes: 4