gpt4 book ai didi

java - 为什么这个 ArrayListStack 在包含元素时抛出 EmptyStackException?

转载 作者:行者123 更新时间:2023-12-02 03:45:00 26 4
gpt4 key购买 nike

我很困惑为什么当我将元素插入 ArrayList 时会抛出异常...这一定是我的 Push() 的问题方法,有人能找到问题吗?我尝试在 if 语句周围加上大括号,但没有成功,甚至可能是 empty() 方法有问题?

这是异常消息:

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

最佳答案

push() 当堆栈为空时不应抛出异常,因为在压入第一个元素之前堆栈将是空的,这很好。

当前,您的第一个 push (list.push('A')) 正在抛出异常,因为堆栈为空。从push 中删除该条件。如果您的堆栈对元素数量有限制,则您应该在 push 中设置一个条件,在堆栈已满时抛出异常。

你的

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

check 应移至 pop() 方法。

编辑:push()方法的Javadoc实际上描述了一个pop()逻辑,它删除堆栈顶部的元素并返回它。在 pop() 中,您的空支票是正确的。

顺便说一句,您在 empty() 中也遇到了错误。 this.size() == 0 应该是 list.size() == 0

关于java - 为什么这个 ArrayListStack 在包含元素时抛出 EmptyStackException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36381953/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com