Reputation: 1
How can you take an array and put it into a stack???? I have a card array with a deck of cards that gets shuffled then I need to change it to a stack and print the first number on top. Anyway anyone can help?
Upvotes: 0
Views: 2366
Reputation: 363
There is not a single line command that would change/convert your array into a stack format. You have to do it yourself.
You haven't posted some code either, so we will have to make some assumptions.
If the array consists of Card-type-objects then what you have to do is this:
Card[] deck; //your array
Stack<Card> deck_stack = new Stack<Card>(); //the newly created stack
//pass the array objects into the stack
for(int i=0; i<deck.length; i++) {
deck_stack.add(deck[i]);
}
//take out the first stack object
System.out.println("Top of the deck: "+deck_stack.pop());
Upvotes: 0
Reputation: 11
To convert array to an stack you need to first convert it to a list and then create a new stack and add all the elements from the list to that stack. Here you can see the reference answer.
String[] stuff = {"hello", "every", "one"};
List<String> list = Arrays.asList(stuff); //1 Convert to a List
//stack.addAll(list);
//3 Add all items from the List to the stack.
// This won't work instead of use the following
Stack<String> stack = new Stack<String>(); //2 Create new stack
// this will insert string element in reverse order, so "hello" will be on top of the stack, if you want order to be as it is, just loop i over 0 to stuff.length.
for(int i = stuff.length - 1; i >= 0; i--) {
stack.add(stuff[i]);
}
System.out.println(stack.pop());//print First Element of Stack
Upvotes: 0
Reputation: 51009
You can use Collections.addAll
Card[] cardsArray;
Stack<Card> cards = new Stack<>();
Collections.addAll(cards, cardsArray);
Upvotes: 2