【发布时间】:2016-07-22 18:32:48
【问题描述】:
我很困惑为什么当我将元素推入ArrayList 时会引发异常...这一定是我的Push() 方法的问题,有人能找到问题吗?我在 if 语句周围尝试了大括号,但没有运气,甚至可能是 empty() 方法的问题?
这是异常消息:
Exception in thread "main" java.util.EmptyStackException
at ArrayListStack.push(ArrayListStack.java:35)
at StackMain.main(StackMain.java:7)
代码:
public class ArrayListStack<E> implements Stack<E> {
// ArrayList to store items
private ArrayList<E> list = new ArrayList<E>();
public ArrayListStack() {
}
/**
* Checks if stack is empty.
* @return true if stack is empty, false otherwise.
*/
public boolean empty() {
return this.size() == 0;
}
/**
* Removes item at top of stack and returns it.
* @return item at top of stack
* @throws EmptyStackException
* if stack is empty.
*/
public E push(E x) {
if (empty())
throw new EmptyStackException();
list.add(x);
return x;
}
//MAIN METHOD
public class MainStack {
public static void main(String[] args) {
ArrayListStack<Character> list = new ArrayListStack<>();
list.push('A');
list.push('B');
list.push('C');
System.out.print(list);
}
}
【问题讨论】:
-
this中的this.size() == 0;是什么? -
有一个size()方法简单的返回size
-
好的,我不确定这个类是否可以扩展 Arraylist
标签: java exception arraylist stack throw