我目前正在处理通用类和堆栈。我创建了一个带有 arrayList 的类,并创建了 push、peek 和 pop 方法。
每当我运行驱动程序时,我都会得到一个边界异常的索引,但我很困惑为什么。任何帮助都会很棒:
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;
}
}
和我的 GenericDriver 类
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());
}
}
如果有人能告诉我为什么我得到这个异常,那就太棒了
最佳答案
你的堆栈看起来像这样:
"One more"
"Hi again"
"how are you?"
"hi"
现在 top
是 4。
当您执行 pop
时,您试图获取 ArrayList 中索引 4
处的元素,但数组是从零开始的在Java中,没有元素4,元素在[0-3]
范围内 你应该在开始时将top
初始化为-1而不是0,所以当你会尝试获取“顶部”元素,你不会得到 IndexOutOfBoundsException
。
关于java - 索引越界异常(堆栈),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20194873/