import java.util.EmptyStackException;
import java.util.Stack;
public class ArrayStack<E> implements TestStack<E>{
private E[] theArray;
private int topOfStack;
public static final int DEFAULT_CAPACITY = 20;
public ArrayStack(){
theArray = (E[])new Object[DEFAULT_CAPACITY];
topOfStack = -1;
}
//overwrite the push meathod
public void push(E data){
if (topOfStack == theArray.length-1);
{
doubleArray();
}
topOfStack++;
theArray[topOfStack]=data;
}
@Override
public E pop() throws EmptyStackException {
if(empty()){
throw new EmptyStackException("Stack pop");
}
E result = theArray[topOfStack];
topOfStack--;
return result;
}
@Override
public E peek() throws EmptyStackException {
if (empty()){
throw new EmptyStackException("Stack peek");
}
return theArray[topOfStack];
}
@Override
public boolean empty() {
return topOfStack == -1;
}
@Override
public int size() {
return topOfStack + 1;
}
private void doubleArray(){
E[] temp =theArray;
theArray = (E[]) new Object[temp.length*2];
for(int i=0; i<temp.length;i++){
theArray[i]=temp[i];
}
}
}
在throw new EmptyStackException("Stack peek")
这里和上面..(“Stack pop")
都在报错,错误显示是EmptyStackException() in EmptyStackException cannot be applied to..
后面就没了,这个就很奇怪了。我也不知道错误是什么,
两个错误:
1 pop 或者 peek 之前你应该先 push 数据
2 EmptyStackException 没有带 String 的构造函数,
throw new EmptyStackException("Stack peek");
和throw new EmptyStackException("Stack pop");
都应该改成throw new EmptyStackException();