Stack help. Why will my peekAtTop() not work??
I am new to Data Structures and am trying to write my own code for a Stack. Everything seems to be working but my peekAtTop() method. I keep getting errors. To test this i just threw in a few strings and displayed them as i popped them off. Let me know if you see anything obvious that I am missing.
import java.util.ArrayList;
public class Stack<T>
{
private ArrayList<T> elements;
private int size;
public Stack()
{
size = 0;
elements = new ArrayList();
}
public void push (T addElement)
{
elements.add(size, addElement);
size++;
}
public T pop()
{
size -=2;
return elements.get(++size);
}
public boolean isEmpty()
{
if(size == 0)
return true;
else
return false;
}
public T peekAtTop()
{
return elements.get(size);
}
}
Re: Stack help. Why will my peekAtTop() not work??
What errors do you get and which lines cause them?
Re: Stack help. Why will my peekAtTop() not work??
Quote:
Originally Posted by
Fubarable
What errors do you get and which lines cause them?
import java.util.*;
public class StackTester {
public static void main(String[] args)
{
System.out.print("This is to test a stack");
System.out.println(" ");
Stack<String> stack = new Stack<String>();
System.out.print(stack.isEmpty());
//add to stack
stack.push("poop");
stack.push("Doop");
stack.push("loop");
stack.push("moop");
System.out.println(stack.peekAtTop());
int count=0;
while(stack.isEmpty() != true)
{
System.out.println(stack.pop());
count++;
System.out.println(count+" removed!");
}
}
}
that is my tester program.
Here is the error.
This is to test a stack
trueException in thread "main" java.lang.IndexOutOfBoundsException: Index: 4, Size: 4
at java.util.ArrayList.RangeCheck(ArrayList.java:547)
at java.util.ArrayList.get(ArrayList.java:322)
at Stack.peekAtTop(Stack.java:39)
at StackTester.main(StackTester.java:20)
Re: Stack help. Why will my peekAtTop() not work??
If there are n elements on the stack, size == n but there is no element #n (that would be the n+1st element); use stack.get(n-1) instead.
kind regards,
Jos
Re: Stack help. Why will my peekAtTop() not work??
In other words, arrays etc use zero based indexing: 0 to length-1.