2016-03-20 41 views
2

下面的代碼誤差一般堆棧類(最好像有溢投入做)

import java.util.EmptyStackException; 

public class MyGenericStack<Item> implements MyGenericStackInterface<Item> { 
private java.util.ArrayList<Item> list = new java.util.ArrayList<Item>(); 

/* 
* Retrieve the item that was most recently added to the stack, 
* which is the item at the top of the stack. 
* The item is removed from the stack. 
*/ 
public Item pop() throws EmptyStackException{ 
    if (isEmpty()) throw new EmptyStackException(); 
    else{ 
     Item thing = null; 
     if(list.get(size()-1) == null){ 
      thing = null; 
     } 
     else{ 

      thing = list.get(size()-1); 
     } 
     return thing; 
    } 
} 

/* 
* Retrieve the item at the top of the stack. 
* Does not modify the stack. 
*/ 
public Item peek() throws EmptyStackException{ 
    if (isEmpty()) { 
     throw new EmptyStackException(); 
    } 
    else{return list.get(size()-1); 

    } 

}; 

/* 
* Add item to the top of the stack. 
*/ 
public void push(Item item){ 

    list.add(item); 
}; 

/* 
* Return true if the stack is empty 
*/ 
public boolean isEmpty(){ 
    return list.isEmpty(); 

} 

/* 
* Return the number of items on the stack 
*/ 
public int size(){ 
    return list.size(); 
}; 


} 

問題是,當我測試所有的情況下,我得到這些8個錯誤

java.lang.AssertionError: IsEmpty Error: isEmpty did not return true for empty stack after underflow. 

java.lang.AssertionError: Peek Error: Peeking at null value on top of stack did not return null. 

java.lang.AssertionError: Pop Error: Popping null value off stack did not return null. 

java.lang.AssertionError: Push Error: Pushed multiple string values, but failed to retrieve them in order (via pop). 

java.util.concurrent.TimeoutException (this test was labelled testReverseStringWithStack) 

java.lang.AssertionError: Size Error: Size did not return correct size after pushes after underflow. 

java.lang.AssertionError: Size Error: Size did not return 0 for empty stack after underflow. 

java.lang.AssertionError: Push Error: Pushed multiple int values, but failed to retrieve them in order (via pop). 

有沒有什麼辦法可以解決這些問題?任何幫助表示讚賞。

+0

雲你給我們展示測試的代碼?它看起來更像是一個測試問題,而不是實際的代碼。 –

回答

0

isEmpty()方法在基礎List<>場來定義,但你的pop()方法實際上並沒有從列表中刪除一個項目 - 它只調用get()列表,它不從列表中刪除的項目上。所以經過幾個電話push()/pop()你會發現isEmpty()size()是不正確的。

0

我可以看到的問題是,當調用pop()時,不會從列表中刪除項目。刪除您從列表中返回的項目。這應該可以解決與下溢有關的錯誤。

0

哇,我感覺有點傻。問題是,我忘記了將「list.remove(size-1)」添加到pop方法中。如果有人沒有指出它,將永遠不會注意到它,謝謝。