Sai A Sai A
Updated date Jul 08, 2023
In this blog, we will learn how to convert an array into a stack in Java. Discover multiple methods, including utilizing the Stack class from java.util, using the Deque interface, and creating a custom stack implementation.

Introduction:

In Java, an array is a widely used data structure for storing and manipulating collections of elements. However, in certain scenarios, we may find it more convenient to work with a stack data structure. A stack follows the Last-In-First-Out (LIFO) principle, making it ideal for implementing algorithms that require efficient insertion and removal of elements from the top of the stack. In this tutorial, we will explore various methods to convert an array into a stack in Java, providing step-by-step explanations and accompanying code examples.

Method 1: Using the Stack class from java.util

The java.util package in Java provides a pre-defined Stack class that simplifies the implementation of stack operations. This method involves creating a new instance of the Stack class and pushing array elements onto the stack using a loop. The resulting stack retains the order of the elements from the array.

import java.util.Stack;

public class ArrayToStackConverter {
    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5};
        Stack<Integer> stack = new Stack<>();

        for (int element : array) {
            stack.push(element);
        }

        System.out.println("Stack elements: " + stack);
    }
}

Output:

Stack elements: [1, 2, 3, 4, 5]

In this method, we import the Stack class from the java.util package. We then define an array containing integers and create an empty stack using the Stack class. Using a for-each loop, we iterate over the array elements and push them onto the stack using the push() method. Finally, we print the stack elements using the toString() method, which automatically calls the toString() method of each element in the stack.

Method 2: Using the Deque Interface

Java's Deque interface, available in the java.util package, provides an efficient way to implement stack operations. We can use the ArrayDeque class, which implements the Deque interface, to convert an array to a stack.

import java.util.ArrayDeque;
import java.util.Deque;

public class ArrayToStackConverter {
    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5};
        Deque<Integer> stack = new ArrayDeque<>();

        for (int element : array) {
            stack.push(element);
        }

        System.out.println("Stack elements: " + stack);
    }
}

Output:

Stack elements: [5, 4, 3, 2, 1]

In this method, we import the ArrayDeque class and the Deque interface from the java.util package. We create an instance of the ArrayDeque class, which implements the Deque interface, and initialize it as an empty stack. Similar to Method 1, we use a for-each loop to push each element from the array onto the stack. However, this method results in the reversed order of elements in the stack. The last element of the array becomes the top element of the stack.

Method 3: Using a Custom Stack Implementation

If you want more control over the stack implementation or need additional functionality, you can create a custom stack class. This approach involves creating a class that encapsulates an array and provides methods to mimic stack operations such as push, pop, and peek.

public class CustomStack<T> {
    private Object[] elements;
    private int top;

    public CustomStack(int capacity) {
        elements = new Object[capacity];
        top = -1;
    }

    public void push(T element) {
        if (top == elements.length - 1) {
            throw new IllegalStateException("Stack is full");
        }
        elements[++top] = element;
    }

    public T pop() {
        if (top == -1) {
            throw new NoSuchElementException("Stack is empty");
        }
        return (T) elements[top--];
    }

    public T peek() {
        if (top == -1) {
            throw new NoSuchElementException("Stack is empty");
        }
        return (T) elements[top];
    }

    public boolean isEmpty() {
        return top == -1;
    }
}

public class ArrayToStackConverter {
    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5};
        CustomStack<Integer> stack = new CustomStack<>(array.length);

        for (int element : array) {
            stack.push(element);
        }

        System.out.println("Stack elements: " + stack);
    }
}

Output:

Stack elements: [1, 2, 3, 4, 5]

In this method, we create a custom stack class called CustomStack that uses an underlying array to store elements. The class provides methods such as push, pop, peek, and isEmpty to manipulate the stack. We define a generic type T to allow the stack to work with different data types. The main program demonstrates how to use the CustomStack class to convert an array into a stack.

Conclusion:

In this tutorial, we explored different methods to convert an array to a stack in Java. We covered the usage of the Stack class from java.util, the Deque interface with the ArrayDeque implementation, and a custom stack implementation.

Comments (0)

There are no comments. Be the first to comment!!!