Results 1 to 2 of 2
  1. #1
    szimme101 is offline Member
    Join Date
    Mar 2008
    Posts
    4
    Rep Power
    0

    Question Traversing through a stack of objects, and puttin them info in an array

    What is a good way to go through a stack of objects?

    I have to compare each object of the stack, to a object I have predifined and then put that object into an array. Stopping this "process" when I find a match.

    Assuming there will be a match and that the stack is not empty what would you recommend I do?


    Thanks,

    SZ

  2. #2
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    10

    Default

    Check the Stack class api in the javadocs to learn what methods are available.
    Java Code:
    import java.util.*;
    
    public class StackTest {
        public static void main(String[] args) {
            String[] names = {
                "Alice", "Sam", "John", "Mary", "Nancy", "Fred"
            };
            String searchFor = "John";
            Stack<String> stack = new Stack<String>();
            for(int i = 0; i < names.length; i++)
                stack.push(names[i]);
            System.out.println("stack = " + stack);
            // Look for searchFor string in stack:
            String[] stackItems = new String[stack.size()];
            int size = stack.size();
            for(int i = 0; i < size; i++) {
                String s = stack.pop();
                if(s.equals(searchFor)) {
                    System.out.println("Found " + searchFor +
                                       " at index of " + i + " in stack.");
                    break;
                }
                stackItems[i] = s;
            }
            System.out.println(Arrays.toString(stackItems));
        }
    }

Similar Threads

  1. Replies: 5
    Last Post: 07-30-2008, 09:30 AM
  2. Creating an array of nonprimitive objects
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-14-2008, 08:46 PM
  3. Array of Objects
    By bluefloyd8 in forum New To Java
    Replies: 5
    Last Post: 01-22-2008, 07:27 PM
  4. Array with objects
    By toby in forum New To Java
    Replies: 1
    Last Post: 07-25-2007, 09:50 AM
  5. array of objects
    By Jack in forum New To Java
    Replies: 2
    Last Post: 07-02-2007, 05:24 AM

Posting Permissions

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