java - OutOfBoundsException 进入堆栈

标签 java stack indexoutofboundsexception

我有一个 ArrayIndexOutOfBoundsException 问题,它总是出现在我的程序中。我怎样才能进入 try{} ?

@Override
    public Object pop() {
        if (stackIsEmpty()) {
            System.err.println("underflow");
            return null;
        } else {
            try {
                Object temp = stack[top];
                stack[top--] = null;
                System.out.println("top is " + top);
                return temp;
            } catch (ArrayIndexOutOfBoundsException e) {
                return "exception";
            }
        }
    }

添加了其余类的代码(我将 -1 与 stackisEmpty() 进行了比较):

public class ArrayStackImpl implements ArrayStack {
    private int top = -1;
    private int maxLength;
    public Object stack[] = new Object[maxLength];

    public ArrayStackImpl(int maxLength) {
        this.maxLength = maxLength;
    }

    @Override
    public boolean stackIsEmpty() {
        return (top < 0);
    }

    @Override
    public void push(Object o) {
        if ((top >= maxLength - 1))
            System.err.println("overflow");
        else
            try {
                stack[++top] = o;
            } catch (ArrayIndexOutOfBoundsException e) {
            }
    }

最佳答案

弹出非空堆栈时,top 可能会变为 -1(表示“空堆栈”)。所以

private int top = -1;

public boolean stackIsEmpty() {
    return top < 0; // != -1
}
<小时/>

在构造函数中进行字段初始化。在此之前maxlength没有初始化,且为0。 此外,您不需要 maxlength 作为字段。 stack.length == maxlength.

public Object[] stack; 

public ArrayStackImpl(int maxLength) {
    stack = new Object[maxLength];

(我使用了更传统的符号Object[]。)

关于java - OutOfBoundsException 进入堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26236108/

相关文章:

java - ArrayIndexOutOfBoundsException 的数组足够大,可以容纳我提供的数据

java - OpenCV 3.0.0 JAR 中缺少 HighGUI

java - Odroid N2 "getGpioList()"返回空数组,无法访问 gpio 端口

java - 查找数组中最小元素的索引 (Java)

c++ - Infix to Postfix to Output (Postfix Calculator) 使用堆栈

java - 从列表中删除范围(尾部)

java.lang.IndexOutOfBoundsException : Index: 7, 大小 : 7. 为什么会发生这种情况?

java - 从 switch 重构多个 case

java - Twitter4j TwitterStream 无法获取所有推文

java - 如何在堆栈的索引处存储多个值?