Stack
This collection is implements LIFO: the last in is the first out. We push elements onto the top of a stack and then pop them for retrieval.
This collection is deprecated—its use is discouraged in favor of Deque. It is based on Vector
, which has worse performance than newer lists.
Let us begin working upon a Stack
. We import java.util.Stack
to make the Stack
type accessible. We use diamond inference syntax to declare the stack.
push()
on the stack. When we push "fly" to the stack, the "fly" is at the top of the stack.Pop()
returns (but does not remove) the topmost element of the stack (in this case "butterfly").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); } }butterfly butterfly worm
A Stack
is based on the Vector
type. We can invoke all the Vector
's methods: here we call add()
instead of push()
to add elements.
for
-loop. In this way we display all the Stack
's elements.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); } } }10 100 20
Stack
is deprecated. It still exists in the Java libraries for compatibility. When I looked for a Stack
collection, it appeared in Eclipse.
ArrayDeque
and the Deque interface
are faster and newer.Stack
and queuesImplementing parsers is often done with stacks. When each element is encountered, it is pushed to the stack. In older programs, this Stack
is used.