Add to stack from ArrayList (Java)

假装没事ソ 提交于 2019-12-08 16:33:28

问题


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<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!


回答1:


Like many collection classes, Stack provides a addAll method :

st.addAll(al)



回答2:


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

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


来源:https://stackoverflow.com/questions/15646487/add-to-stack-from-arraylist-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!