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).

有什么办法可以解决这些问题吗?任何帮助表示赞赏。

4

3 回答 3

0

您的isEmpty()方法是根据基础List<>字段定义的,但您的pop()方法实际上并未从列表中删除项目 - 它仅调用get()列表,不会从列表中删除项目。因此,在几次致电push()/之后,pop()您会发现这是不正确的。isEmpty()size()

于 2016-03-20T18:03:33.700 回答
0

我可以看到的问题是,当pop()被调用时,项目不会从列表中删除。从列表中删除您返回的项目。这应该解决与下溢相关的错误。

于 2016-03-20T18:06:38.170 回答
0

哇,我觉得有点傻。问题是我只是忘记在 pop 方法中添加“list.remove(size-1)”。如果没有人指出,永远不会注意到它,谢谢。

于 2016-03-20T18:25:32.727 回答