C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Push: We invoke push() on the stack. When we push "fly" to the stack, the "fly" is at the top of the stack.
Then: When we push "worm" and "butterfly" to the stack, the fly is now at the bottom, and "butterfly" is at the top.
Peek: This returns (but does not remove) the topmost element of the stack (in this case "butterfly").
Pop: We call pop() twice to remove the topmost element, and then the new topmost element. We display both results.
Java program that uses Stack
import java.util.Stack;
public class Program {
public static void main(String[] args) {
Stack<String> stack = new Stack<>();
stack.push("fly");
stack.push("worm");
stack.push("butterfly");
// Peek at the top of the stack.
String peekResult = stack.peek();
System.out.println(peekResult);
// Pop the stack and display the result.
String popResult = stack.pop();
System.out.println(popResult);
// Pop again.
popResult = stack.pop();
System.out.println(popResult);
}
}
Output
butterfly
butterfly
worm
Loop: We can loop over a stack with its iterator in a for-loop. In this way we display all the Stack's elements.
ForJava program that uses add, loop
import java.util.Stack;
public class Program {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
stack.add(10);
stack.add(20);
stack.add(1, 100); // We can add at a position.
// Loop over int values.
for (int value : stack) {
System.out.println(value);
}
}
}
Output
10
100
20
However: This is not the best stack-like collection. The ArrayDeque and the Deque interface are faster and newer.
ArrayDequeNote: In my experience, when a framework redesigns collections and replaces them, the newer ones are consistently better.