我们如何将一个堆栈完全弹出到另一个堆栈中
我有这个代码:
for (int i = 0; i < StackA.capacity(); i++) {
StackB.push(StackA.get(i));
}
但是这给了我这个错误:
Array index out of range: 0
at java.base/java.util.Vector.get
有人可以帮助我确定自己的错误吗?
I have this code:
for (int i = 0; i < StackA.capacity(); i++) {
StackB.push(StackA.get(i));
}
but it's giving me this error:
Array index out of range: 0
at java.base/java.util.Vector.get
Can anybody help me identify my mistake?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您正在寻找的是如何将元素添加到
stackb
而无需删除atacka
的元素,那么您可以使用Iterator
来traverse 代码> stacka ,然后将其元素添加到stackb
中。否则,正如注释中建议的那样,如果在
stacka
中消耗元素不是问题,那么您可以简单地迭代第一个堆栈,直到它为空并将每个元素弹出到stackb 在每次迭代期间。
If what you're looking is how to add elements into
stackB
without removing the elements fromatackA
, then you could use anIterator
to traversestackA
and add its elements intostackB
.Otherwise, as it has been suggested in the comments, if consuming the elements within
stackA
is not a problem, you could simply iterate your first stack until it's empty and popping each element intostackB
during every iteration.