Add to stack from ArrayList (Java)

19,740

Solution 1

Like many collection classes, Stack provides a addAll method :

st.addAll(al)

Solution 2

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

for(String str : al)
  st.push(str)
Share:
19,740
A C
Author by

A C

Noob Java programmer :(

Updated on July 11, 2022

Comments

  • A C
    A C almost 2 years

    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!

    • jahroy
      jahroy about 11 years
      You can read the documentation for Stack here. Stacks also implement Collection, so you can also use any of the methods you see here. It's always a good idea to read the documentation about classes when you use them ;-)
    • mihsathe
      mihsathe about 11 years
      There's no need to -1 this question. We were all new at this at some point of time.