2016-04-03 54 views
0

我很困惑,爲什麼當我將元素推入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); 
    } 
} 
+0

this.size()== 0中的'this'是什麼? –

+0

有一個size()方法,只是返回大小 – Peanutcalota

+0

好吧,我不確定該課程是否可能擴展Arraylist –

回答

1

push()當堆棧爲空不應該拋出一個異常,因爲這將是推動第一個元素之前空,這很好。

目前你的第一個pushlist.push('A'))正在拋出一個異常,因爲堆棧是空的。從push中刪除該條件。如果您的堆棧對元素數量有限制,則應在push中有一個條件,如果堆棧已滿,則會引發異常。

if (empty()) 
     throw new EmptyStackException(); 

檢查應該被移到pop()方法。

編輯:你的push()方法的Javadoc實際上描述了一個pop()邏輯,它刪除堆棧頂部的元素並返回它。在pop()您的空支票將是正確的。

順便說一句,你也有一個錯誤empty()this.size() == 0應該是list.size() == 0

+0

非常有幫助!感謝您也收到錯誤! – Peanutcalota

1

因爲你把你的第一個元素數組中的那一刻使用的代碼

list.push('A'); 

它會拋出該異常,因爲當時的數組將爲空。

理想情況下,當您嘗試從陣列中刪除某些元素而不是在添加時,應該拋出此異常。

0
/** 
* Removes item at top of stack and returns it. 
* @return item at top of stack 
* @throws EmptyStackException 
*    if stack is empty. 
*/ 
public E pop() { 
    if (empty()) 
     throw new EmptyStackException(); 
    E x = list.remove(0); 
    return x; 
} 
/** 
* Add item at bottom of stack. 
*/ 
public void push(E x) { 
    list.add(x); 
} 

當我們試圖從List中移除/獲取某些東西時,應拋出EmptyStackException。注意:如果多個線程嘗試並行推送和彈出,則上面的代碼不是線程安全的。然後輸出與預期不同。

相關問題