How to Convert Stack to Array in Java

How to Convert Stack to Array in Java ? In Java, the Stack class, part of the java.util package, represents a Last-In-First-Out (LIFO) data structure. Occasionally, there arises a need to convert the elements of a Stack into an array for various operations or ease of manipulation. Fortunately, Java provides a straightforward method to achieve this conversion using the toArray() method present in the Stack class.

Using the toArray() Method

The toArray() method in Java’s Stack class enables the conversion of a Stack into an array. This method returns an array containing all the elements of the stack in the same order as they are found in the stack, where the top element of the stack becomes the last element in the array.

Syntax:
Object[] toArray()

The toArray() method, when applied to a Stack object returns an array of type Object. This array can then be further cast to the appropriate type if the elements in the stack are of a specific class or type.

Example of Converting Stack to Array in Java

Let’s see an example demonstrating the conversion of a Stack of integers to an array

import java.util.Stack;
import java.util.Arrays;

public class StackToArrayExample {
    public static void main(String[] args) {
        // Create a Stack and add elements
        Stack<Integer> stack = new Stack<>();
        stack.push(10);
        stack.push(20);
        stack.push(30);
        stack.push(40);

        // Convert the Stack to an array
        Integer[] array = stack.toArray(new Integer[stack.size()]);

        // Display the elements in the array
        System.out.println("Elements in the array obtained from Stack:");
        System.out.println(Arrays.toString(array));
    }
}

Output

How to Convert Stack to Array in Java

In this example, a Stack of integers is created and populated with elements (10, 20, 30, 40) using the push() method. The toArray() method is then utilized to convert the Stack to an array of Integer type by passing an appropriately sized Integer array to accommodate the stack’s elements.

Converting a Stack to an array in Java is simplified by using the toArray() method available in the Stack class. This method offers a convenient way to obtain an array containing the elements of the stack, enabling us to perform array-based operations or manipulations on the elements previously held in the stack.

See Also

1 thought on “How to Convert Stack to Array in Java”

Leave a Comment