从 ArrayList (Java) 添加到堆栈

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15646487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 20:24:36  来源:igfitidea点击:

Add to stack from ArrayList (Java)

javaarrayliststack

提问by A C

I have an ArrayList pre-defined with hardcoded values. How do I add these to a stack? The idea is to demonstrate the pop, push, peek functions of the stack class.

我有一个用硬编码值预定义的 ArrayList。如何将这些添加到堆栈中?这个想法是为了演示stack类的pop、push、peek函数。

ArrayList<String> al = new ArrayList<String>();

al.add("A");
al.add("B");
al.add("C");

Stack<String> st = new Stack<String>();

st.push(al); **// This doesn't seem to work.. Will I have to loop it in some way?**

System.out.println(st);

Thanks!

谢谢!

回答by Denys Séguret

Like many collection classes, Stackprovides a addAllmethod :

像许多集合类一样,Stack提供了一个addAll方法:

st.addAll(al)

回答by noMAD

Why not just iterate over array list and push it to stack?

为什么不只是遍历数组列表并将其推送到堆栈?

for(String str : al)
  st.push(str)