In this tutorial, you will learn the basic implementation of Stack
with Java. You will also quickly walk through some official supports in Java such as java.util.Deque
, java.util.concurrent.BlockingDeque
and java.util.Stack
What is Stack?
Stack is a linear data structure of similar data type items, stores data in LIFO (Last In First Out) order
Basic operations
push
adds an item onto the stackpop
removes last pushed item from the stackpeek
returns the last item pushed onto the stack
Other operations
isEmpty
returns true if no more items can be poppedisFull
returns true if no more items can be pushedsize
returns the number of items on the stack
Stack implementation by Array
Application
- Depth First Search uses a stack to track which elements to visit next
Stack in Java
java.util.Deque
(interface), since Java 1.6, unsynchronized. For example
Deque<Integer> stack = new ArrayDeque<>();
stack.push(1);
stack.peek();
stack.pop();
java.util.concurrent.BlockingDeque
(interface), since Java 1.6, synchronized / thread-safe. For example
BlockingDeque<Integer> stack = new LinkedBlockingDeque<>();
stack.push(1);
stack.peek();
stack.pop();
java.util.Stack
(class), since Java 1.1, extendsVector
, synchronized, should not be used due to its negative impact on performance