Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add to stack from ArrayList (Java)

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!

like image 397
A C Avatar asked Mar 26 '13 20:03

A C


2 Answers

Like many collection classes, Stack provides a addAll method :

st.addAll(al)
like image 110
Denys Séguret Avatar answered Oct 18 '22 01:10

Denys Séguret


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

for(String str : al)
  st.push(str)
like image 2
noMAD Avatar answered Oct 18 '22 01:10

noMAD