Working with Stack Data Structure in Java using Stack Class and ArrayDeque

Java Collection Framework provides a Stack class that implements a Stack data structure based on the last-in-first-out principle. The class provides basic push and pop operations, as well as three additional functions: empty, search, and peek. It can be considered as a subclass of Vector and extends it with the five mentioned functions.

Stack in Java


It's important to note that the Stack class in Java is a legacy class and inherits from Vector in Java. Although it's thread-safe, it involves overhead when we don't need thread safety. Thus, it's recommended to use ArrayDeque for stack implementation as it's more efficient in a single-threaded environment.

ArrayDeque


Here's an example implementation of Stack using ArrayDeque:

import java.util.ArrayDeque; public class StackExample { public static void main(String[] args) { ArrayDeque<Integer> stack = new ArrayDeque<>(); stack.push(10); stack.push(20); stack.push(30); System.out.println(stack.peek()); System.out.println(stack.pop()); System.out.println(stack.peek()); } }

The output of the above code is:

30

30

20

Another example implementation of Stack using ArrayDeque to demonstrate its size and empty functions:


import java.util.ArrayDeque; public class StackExample { public static void main(String[] args) { ArrayDeque<Integer> stack = new ArrayDeque<>(); stack.push(10); stack.push(20); stack.push(30); System.out.println(stack.size()); System.out.println(stack.isEmpty()); } }

The output of the above code is:

3 false

The Stack class in Java provides the following methods:

Method

Description

Time Complexity

push(Object element)

Pushes an element on the top of the stack.

O(1)

pop()

Removes and returns the top element of the stack. An 'EmptyStackException' exception is thrown if we call pop() when the invoking stack is empty.

O(1)

peek()

Returns the element on the top of the stack, but does not remove it.

O(1)

isEmpty()

Returns true if nothing is on the top of the stack. Else, returns false.

O(1)

size()

Returns the size of the stack or the number of elements present in the stack.

O(1)

In conclusion, the Stack class in Java provides a simple and efficient way of implementing the stack data structure in Java. However, it's important to note that it's a legacy class and might not be the best choice in certain scenarios. Using ArrayDeque instead can provide a more efficient solution in a single-threaded environment.


Previous Post Next Post