【问题标题】:How to push Stack content to an array in Java? [closed]如何将堆栈内容推送到 Java 中的数组? [关闭]
【发布时间】:2014-04-28 02:47:41
【问题描述】:

我有一个我想编写的方法,它有一个整数堆栈作为参数,我想将这个堆栈中的所有内容推送到我在该方法中创建的整数数组中。我该怎么做?

public void test(StackADT<Integer> stack)

{

SimpleListADT<Integer> values = new ArraySimpleList<Integer>();
// I want to push the content of the stack in the parameter to the list
// using a loop; the stacks will contain integers but they will be represented 
// as strings, not sure if I have the for loop set up correctly

for (int i = 0; i < stack.size();i++)
{
  String s = stack.get(i);
  values.addToRear(s); 
  // not sure what to put in the body of the loop here, I know the above is
  // incorrect because there's no get(int) method for stacks, I just need a
  // push in the right direction
}

}

【问题讨论】:

  • 查看如何遍历集合。 SO 不是要求为您完成编码的地方。
  • 什么数组?另外,您的 StackADT 是如何实现的? pop()?
  • StackADT 不是 Java 定义的包,因此我们对它一无所知,无法帮助您使用它。
  • 您需要告诉我们这些类的 API,因为它们不是标准的 Java 集合类。 SimpleListADT 是否实现 java.util.ListStackADT呢?

标签: java arrays stack push element


【解决方案1】:

Stacks 使用pushpop 方法。 Push 将一个元素添加到堆栈中,而 pop 删除一个元素。您可能还可以访问 peek 以获取堆栈的第一个(最顶部)元素,而无需删除它。

你可能想做类似的事情

while (!stack.isEmpty) {
 otherCollection.add(stack.pop());
}

【讨论】:

  • 这正是我所需要的。谢谢。
猜你喜欢
  • 2016-05-31
  • 1970-01-01
  • 1970-01-01
  • 2011-08-29
  • 1970-01-01
  • 2019-04-26
  • 2021-11-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多