Reputation: 93
I've has a look around and can't seem to fins an answer.
In Java, if I have a stack with 10 items, is there a way to look at the 4th item without altering the stack?
Thanks in advance.
Upvotes: 0
Views: 1206
Reputation: 2307
Its possible to see element at specific index in Java's java.util.Stack
:
Stack<String> stack = new Stack<>();
// adding multiple elements to stack
stack.elementAt(3);
Reason for this is because Stack is extending Vector
and elementAt is Vectors method... Also, Vector has the following public method:
stack.get(3);
So this will work too...
And Vector is basically wrapping array, so it will work in O(1)
.
This of course, goes against theoretical Stack, but most of data structures in Java are different, they mostly wrap basic array so you end up having more functionalities...
Upvotes: 1