我对ArrayIndexOutOfBoundsException有一个问题,它总是出现在我的程序中。我怎么才能尝试{}?
@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";
}
}
}添加了rest类的代码(我在stackisEmpty()中与-1进行了比较):
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) {
}
}发布于 2014-10-07 12:43:24
在弹出非空堆栈时,top可能变成-1 (用于“空堆栈”)。所以
private int top = -1;
public boolean stackIsEmpty() {
return top < 0; // != -1
}在构造函数中执行字段初始化。在该最大长度未被初始化之前,和0。此外,您不需要使用maxlength作为字段。stack.length == maxlength。
public Object[] stack;
public ArrayStackImpl(int maxLength) {
stack = new Object[maxLength];(我使用了更传统的表示法Object[]__。)
发布于 2014-10-07 12:39:06
将顶部初始化为-1。不要抓住ArrayIndexOutOfBoundsException,找出原因。另外,您的stackIsEmpty应该检查top是否等于-1。
https://stackoverflow.com/questions/26236108
复制相似问题