Reputation: 101
(This is using the java.util.Stack)
In my code I got a value, lets say a string "1" and I want to put that at the bottom of this stack of numbers.
"4"
"3"
"2"
Now the methods I have for the java.util.Stack don't actually come with a way I can just send my value of "1" to the bottom of this stack, they instead only let me push the value to the top of the stack which isn't any good to me.
Is there a way I can send "1" to the bottom of this stack?
Upvotes: 0
Views: 3409
Reputation: 49656
It's a stack, a last-in-first-out data structure. Fundamentally, you can't add to the bottom unless it's empty.
You may want to use a different data type, I think java.util.Deque would work for you.
Upvotes: 1
Reputation: 40057
You can do it like this. The add
method allows you to put a value anywhere in the stack. But you're basically subverting the nature of the stack. Stacks are meant to be LIFO (last in, first out). You may want to rethink your design if this is what you want to do. There are various Collection
implementations from which you can choose. Check the API and read the documentation to see which one best suits your needs.
Stack<Integer> stack = new Stack<>();
stack.push(4);
stack.push(3);
stack.push(2);
stack.add(0,1);
while(!stack.isEmpty()) {
System.out.println(stack.pop());
}
prints
2
3
4
1
Upvotes: 1
Reputation: 31
You actually can't. You can only push and pop the top element of the stack. If you wish to access your data structure both by top and bottom at the same time, you should use another data structure. Try using the LinkedList class instead which offers what you want to do.
Upvotes: 0