Results 1 to 2 of 2
- 03-25-2008, 01:18 AM #1
Member
- Join Date
- Mar 2008
- Posts
- 4
- Rep Power
- 0
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
- 03-25-2008, 05:06 AM #2
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
-
How do you read from a file, and then store the info in an array?
By szimme101 in forum New To JavaReplies: 5Last Post: 07-30-2008, 09:30 AM -
Creating an array of nonprimitive objects
By Java Tip in forum java.langReplies: 0Last Post: 04-14-2008, 08:46 PM -
Array of Objects
By bluefloyd8 in forum New To JavaReplies: 5Last Post: 01-22-2008, 06:27 PM -
Array with objects
By toby in forum New To JavaReplies: 1Last Post: 07-25-2007, 09:50 AM -
array of objects
By Jack in forum New To JavaReplies: 2Last Post: 07-02-2007, 05:24 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks