Viraj Tharinda
Viraj Tharinda

Reputation: 29

read last value from stack (java)

I created stack for store values as follows. I need to read last value from stack without using "stack.pop".

import java.util.Stack;

Stack stack = new Stack();
stack.push("Something");
stack.push("Something new");

Upvotes: 1

Views: 9302

Answers (1)

G_H
G_H

Reputation: 12009

Class Stack extends class Vector, which has a lastElement() and firstElement() method that will return the last respectively first element in the collection.

After doing a test I can confirm that the top of the stack (the last element pushed in) is the last element, the bottom of the stack the first element. Also note that if such access is necessary, it might indicate you need a different data structure than a stack, but that depends on context. At any rate, Vector allows for random access.

If you just need the last element by this definition without popping it, using peek() as suggested by Elliott in his comment would be the appropriate method.

Upvotes: 1

Related Questions