Java 泛型堆栈类中的错误(大多数似乎与下溢输入有关)

Java 泛型堆栈类中的错误(大多数似乎与下溢输入有关),java,arrays,stack,underflow,Java,Arrays,Stack,Underflow,这是密码 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 w

这是密码

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();
};


}

我有什么办法可以修这些吗?非常感谢您的帮助。

您的
isEmpty()
方法是根据基础的
List
字段定义的,但是您的
pop()
方法实际上并没有从列表中删除项目-它只调用列表上的
get()
,而不会从列表中删除项目。因此,在对
push()
/
pop()
进行了几次调用之后,您会发现
isEmpty()
size()
不正确。

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

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

Cloud你给我们看测试代码了吗?在我看来,与实际代码相比,测试更像是一个问题。
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).