如何在Java中将Stack内容推送到数组?

时间:2014-03-20 22:51:58

标签: java arrays stack push element

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

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
}

}

1 个答案:

答案 0 :(得分:0)

Stack使用pushpop方法。 Push向堆栈添加元素,而pop删除元素。您可能还可以访问peek以获取堆栈的第一个(最顶层)元素而不删除它。

您可能想要执行类似

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