Results 1 to 3 of 3
  1. #1
    pompeez is offline Member
    Join Date
    Aug 2007
    Posts
    2
    Rep Power
    0

    Default how to convert a Java array to a java stack?

    Hi,
    I would like to convert a Java Arraylist/array/list to an equivalent Java stack, such that the last element in the array becomes the forst element in the stack. The array I have is nested.
    Thanks for your time!
    Pompeez

  2. #2
    shanePreater is offline Member
    Join Date
    Jul 2007
    Location
    England, Bath
    Posts
    47
    Rep Power
    0

    Default

    The following code shows how to convert an array into a stack. If you have a List to start with simply skip step 1.
    Java Code:
    String[] stuff = {"this", "and", "that"};
    		List<String> list = Arrays.asList(stuff); //1 Convert to a List
    		Stack<String> stack = new Stack<String>(); //2 Create new stack
    		stack.addAll(list); //3 Add all items from the List to the stack.
    Hope that sorts you out,
    Shane.

  3. #3
    shanePreater is offline Member
    Join Date
    Jul 2007
    Location
    England, Bath
    Posts
    47
    Rep Power
    0

    Default

    Oops I misread that you needed to reverse add it all so replace number 3 above with:
    List
    Java Code:
    for(int i = list.size() - 1; i >= 0; i--) {
    stack.add(list.get(i));
    }
    Array
    Remove step 1 as its not needed anymore.
    Java Code:
    for(int i = stuff.length - 1; i >= 0; i--) {
    stack.add(stuff[i]);
    }

Similar Threads

  1. Stack data structure in Java
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-16-2008, 10:34 PM
  2. Demonstration of Stack class in java.util package
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-16-2008, 10:33 PM
  3. How to use Stack class in java.util package
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-16-2008, 10:32 PM
  4. Replies: 1
    Last Post: 03-25-2008, 05:06 AM
  5. Using java.util.Stack
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 11-20-2007, 05:17 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
  •