我很困惑,爲什麼當我將元素推入ArrayList
時,我得到一個異常......這肯定是我的Push()
方法的一個問題,任何人都可以找到問題嗎?我在if語句中嘗試了大括號,但沒有運氣,甚至可能是empty()
方法的問題?爲什麼當ArrayListStack包含元素時拋出EmptyStackException?
這裏是異常消息:
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.size()== 0中的'this'是什麼? –
有一個size()方法,只是返回大小 – Peanutcalota
好吧,我不確定該課程是否可能擴展Arraylist –