Stack Java Library
Last Updated :
03 Nov, 2024
Improve
In Java, there are multiple ways to use built-in libraries for Stack.
Stack Class
- It is a legacy collection from early Java versions. It is outdated and rarely used in modern Java
- It's synchronized and thread-safe, which can be slower in single-threaded applications like doing data structures and CP problems.
- Synchronized by default, which might add unnecessary overhead if thread-safety isn't required.
ArrayDeque Class
- Faster performance for single-threaded scenarios.
- Resizable array-backed without the overhead of synchronization.
- More flexible, as it can also be used as a queue.
- Cannot store
null
elements (throwsNullPointerException
if attempted).
If you are not sure for a coding problem, you may always use this for fast performance.
import java.util.ArrayDeque;
import java.util.Deque;
public class GFG {
// Driver Code
public static void main(String[] args)
{
// Creating an ArrayDeque to use
// as a Stack
Deque<Integer> s = new ArrayDeque<Integer>();
// Inserting elements in the Stack
// using push() operation
s.push(17);
s.push(19);
s.push(15);
// Printing the elements
System.out.println("Stack after insertion: " + s);
// Removing elements from the Stack
// using pop() operation
s.pop();
System.out.println("Stack after deletion: " + s);
s.pop();
System.out.println("Stack after deletion: " + s);
}
}
Output
Stack after insertion: [15, 19, 17] Stack after deletion: [19, 17] Stack after deletion: [17]
LinkedList Class
- Also implements
Deque
and can be used as a stack, queue, or double-ended queue. It is a doubly-linked list implementation. - We use
LinkedList
when we want to leverage linked list operations like insertions and deletions are required at both ends. - More memory overhead as we used linked list.
Feature | Stack | ArrayDeque | LinkedList |
---|---|---|---|
Synchronization | Yes | No | No |
Backing Structure | Array (Vector) | Resizable Array | Doubly-Linked List |
Null Elements | Yes | No | Yes |
Use as Queue | No | Yes | Yes |
Performance | Slower | Fastest | Moderate |
Memory Overhead | Moderate | Low | High |
Thread Safety | Synchronized | Not thread-safe | Not thread-safe |