我正在用Java语言编写简单的堆栈,但是在编译我的push方法时会导致错误“ java:未报告的异常StackOverflowException;必须被捕获或声明为抛出”。
我认为可以通过在方法中添加throws子句来解决此问题,但仍然出现错误。怎么了?
import java.util.ArrayList;
公共类堆栈{
// the maximum size of the stack
protected int stackSize;
// the internal structure of the stack
protected ArrayList<T> stack;
// the last popped element
protected T lastPoppedElement;
// the constructor
public Stack(int size) {
stack = new ArrayList<>();
stackSize = size;
}
public void push(T newElement) throws StackOverflowException {
StackOverflowException e = new StackOverflowException();
if(this.stackSize == this.stack.size()){
throw e;
}else{
this.stack.add(newElement);
}
}
public T pop() {
try{
this.lastPoppedElement = this.stack.get(this.stack.size() -1);
return this.lastPoppedElement;
}catch(IndexOutOfBoundsException e){
System.out.println("The stack is empty.");
T r = (T) this.lastPoppedElement;
return r;
}
}
public static void main( String[] args )
{
Stack t = new Stack<>(5);
t.push("hello");
t.pop();
System.out.println(t);
}
}