[英]errors in a generic stack class (most seem to do with underflow inputs)
這是代碼
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).
有什么辦法可以解決這些問題? 任何幫助表示贊賞。
您的isEmpty()
方法是根據基礎List<>
字段定義的,但是您的pop()
方法實際上並未從列表中刪除項目-它僅調用列表中的get()
,但不會刪除該項目從列表中。 因此,在幾次調用push()
/ pop()
您會發現isEmpty()
和size()
不正確。
我所看到的問題是,當調用pop()
時,則沒有從列表中刪除項目。 從列表中刪除您返回的項目。 這樣可以消除與下溢有關的錯誤。
哇,我有點傻。 問題是我只是忘記在pop方法中添加“ list.remove(size-1)”。 如果有人沒有指出,那就永遠不會注意到它了,謝謝。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.