How to convert a stack to an array in Java?

In this tutorial, we will learn how to convert stack to array in Java.

Firstly, we need to know the basic concepts of stack and array.

Array is a collection of elements stored in contiguous memory locations. Elements in an array using index number.

Stack is a data structure which follows the LIFO(Last In First Out) concept. Here, elements cannot be accessed directly. We can understand this with the example of a pile of plates. The plate at the top(Last in) has to be removed first(First out) in order to get the plate which is at the bottom.

Java Code to convert a stack to an array

import java.util.Stack;
public class Sta{
    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<>();
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);
        Object[] arr = stack.toArray();
    System.out.println("Array elements are :");
        for (Object ele : arr) {
            System.out.println(ele);
        }
    }
}

Explanation

In the 1st line, we include the Stack class from the java. util package in our program. This is done to use the Stack class without needing to specify its full package name every time.

Inside the main method,  a variable named stack is created of type Stack<Integer> that can hold <Integer> objects. Integers 1,2,3 and 4 are pushed(inserted) into the stack.

The statement in line 9 means that we are converting a Stack to an array of Object type.

The array elements are then printed.

Output

The following output will be generated after executing the above code:

Array elements are:

1

2

3

4

Leave a Reply

Your email address will not be published. Required fields are marked *