Results 1 to 6 of 6
  1. #1
    Ciwan is offline Banned
    Join Date
    Dec 2008
    Location
    Earth
    Posts
    87
    Rep Power
    0

    Question Stack to an ArrayList<String>

    Hi Guys

    Can someone please tell me how I can convert a Stack object to an ArrayList<String> object ?

    I know that a Stack has a method called .toArray() but that gives me ArrayList<Object>.

    I then googled how to convert a ArrayList<Object> to an ArrayList<String> and got nothing :(

    I would greatly appreciate any help.

    thank you.

  2. #2
    Join Date
    Nov 2010
    Posts
    26
    Rep Power
    0

    Default

    Perhaps create a new ArrayList<String> and then copy manually.
    Java Code:
    for(Object o : oldArray){
       newArray.add((String) o)
    }
    Something like that?

  3. #3
    doWhile is offline Moderator
    Join Date
    Jul 2010
    Location
    California
    Posts
    1,641
    Rep Power
    7

    Default

    Stack implements Collection, and ArrayList has a constructor which accepts a Collection as a Parameter. If the stack has a Generic type Object (eg Stack<Object> ), then iterate over the stack, adding the Objects to the List by casting or calling the toString() method (safer)
    Last edited by doWhile; 05-22-2011 at 01:58 AM.

  4. #4
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,578
    Rep Power
    25

    Default

    Can you change the Stack to Stack<String>?

  5. #5
    Ciwan is offline Banned
    Join Date
    Dec 2008
    Location
    Earth
    Posts
    87
    Rep Power
    0

    Default

    Yep it already is Stack<String>. sorry that I didn't mention that earlier.

  6. #6
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,578
    Rep Power
    25

    Default

    how I can convert a Stack object to an ArrayList<String> object
    Have you tried this:
    Stack<String> ss = new Stack<String>();
    ....
    ArrayList<String> al = new ArrayList<String>(ss);

Similar Threads

  1. Stack (collection) to int via String
    By aborgeld in forum New To Java
    Replies: 7
    Last Post: 04-07-2011, 05:16 PM
  2. Replies: 12
    Last Post: 11-26-2010, 08:33 AM
  3. Replies: 1
    Last Post: 11-24-2010, 08:47 PM
  4. Replies: 1
    Last Post: 11-04-2010, 06:53 PM
  5. Putting a string into ArrayList<String>
    By k4ff1n34dd1c7 in forum New To Java
    Replies: 5
    Last Post: 03-23-2009, 05:10 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •