java - 索引越界异常(堆栈)

标签 java generics stack

我目前正在处理通用类和堆栈。我创建了一个带有 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"    

现在 top4

当您执行 pop 时,您试图获取 ArrayList 中索引 4 处的元素,但数组是从零开始的在Java中,没有元素4,元素在[0-3]范围内 你应该在开始时将top初始化为-1而不是0,所以当你会尝试获取“顶部”元素,你不会得到 IndexOutOfBoundsException

关于java - 索引越界异常(堆栈),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20194873/

相关文章:

c# - 使泛型成为变量

c# - 如何从泛型列表中提取派生类型?

c++ - 创建一副纸牌

c - 使用堆栈平衡括号

c - 为什么我的代码破坏了堆栈?我该如何修复它?

Java while循环和随机方法

java - org.apache.struts.chain.commands.servlet.CreateAction createAction 信息 : Initialize action of type:

java - 为什么当 Intent 双值时我得到 null

java - 调用 JAR 时如何保持内部/隐藏数据库连接打开?

带有泛型的 Java 反射方法调用