我有一个 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/