【发布时间】:2014-05-05 11:24:18
【问题描述】:
嘿,我有一个问题,为什么我的程序会抛出 ArrayIndextOutofBounds 异常 我在互联网上到处查看并浏览了代码,但我知道我遗漏了一些东西。 这是我第一个实现堆栈的程序,坦率地说,我并不是 100% 了解我正在做的事情。
我认为问题出在我的 isEmpty 方法上,但无法准确看出我做错了什么。必须有一种更简单的方法来测试堆栈是否为空? 任何帮助将不胜感激。
PS:我的测试堆栈设置正确吗?
这是我的代码:
import java.util.Arrays;
public class ArrayStack<T> implements StackADT<T>
{
private final static int DEFAULT_CAPACITY = 100;
private int top;
private T[] stack;
private int emptyCount = 0;
//Creates an empty stack using the default capacity.
public ArrayStack()
{
this(DEFAULT_CAPACITY);
}
//Creates an empty stack using the specified capacity.
@SuppressWarnings("unchecked")
public ArrayStack(int initialCapacity)
{
top = 0;
stack = (T[])(new Object[initialCapacity]);
}
/* Adds the specified element to the top of this stack, expanding
the capacity of the array if necessary.*/
public void push(T element)
{
if (size() == stack.length)
expandCapacity();
stack[top] = element;
top++;
}
/*Creates a new array to store the contents of this stack with
twice the capacity of the old one.*/
private void expandCapacity()
{
stack = Arrays.copyOf(stack, stack.length * 2);
}
/*Removes the element at the top of this stack and returns a
reference to it.*/
public T pop() throws EmptyCollectionException
{
if (isEmpty())
throw new EmptyCollectionException("stack");
top--;
T result = stack[top];
stack[top] = null;
return result;
}
/*Returns a reference to the element at the top of this stack.
The element is not removed from the stack.*/
public T peek() throws EmptyCollectionException
{
if (isEmpty())
throw new EmptyCollectionException("stack");
return stack[top-1];
}
//Returns true if this stack is empty and false otherwise.
public boolean isEmpty()
{
for(int i = 0; i < stack.length; i++)
{
if (stack[i] == null)
emptyCount++;
}
if(emptyCount != stack.length-1)
return false;
else
return true;
}
//Returns the number of elements in this stack.
public int size()
{
return stack.length;
}
//Returns a string representation of this stack.
public String toString()
{
String output = "The element at the top of the stack is: " + peek() + "\n" +
"It is " + isEmpty() + " that the stack is empty." + "\n" +
"The number of elements in the stack is: " + size();
return output;
}
}
还有我的驱动程序/测试文件:
public class StackTest
{
public static void main(String[] args) throws EmptyCollectionException
{
ArrayStack stack = new ArrayStack(5);
System.out.println(stack);
}
}
【问题讨论】:
标签: java arrays generics stack indexoutofboundsexception