In this tutorial, you will learn the basic implementation of Stack
with Java. You will also quickly walk through some official supports of Stack in Java such as java.util.Deque
, java.util.concurrent.BlockingDeque
and java.util.Stack
What is Stack Data Structure?
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
Implementation
You can implement a stack with either a linked list
or an array
(static or dynamic)
Stack implementation example with Static Array
Application
- Depth First Search uses a stack to track which elements to visit next
Stack implementations in Java
java.util.Deque
(interface), since Java 1.6, unsynchronized / not thread-safe, using in single threaded environment. 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, using in multi threaded environment. 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