How to Convert stack to array in Java
In this tutorial, we will see how to convert a Stack into an Array using Java programming language.
A stack is a linear data structure that follows the Last In, First Out (LIFO) principle.
An array is a linear data structure that stores a collection of elements of the same data type.
Before doing so, let’s see what all basic functions a stack has:
- push(): inserts an element on top of the stack.
- pop(): removes an element from top of the stack.
- peek(): returns the value of the element at the top.
Refer, implementing Stack in java Stack in Java for better understanding.
Also, let’s see what all basic functions an array has:
- insertion: add an element to a specific position in the array.
- deletion: remove an element from a specific position in the array.
- traversal: access each element of the array .
Code to convert stack to array in Java
import java.util.Scanner; import java.util.Stack; public class StackToArray { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Create a stack to store the elements Stack<Integer> stack = new Stack<>(); // Assign size to the stack System.out.println("Enter the size of stack:"); int n = scanner.nextInt(); // Read input elements and push them into the stack System.out.println("Enter the elements:"); for (int i = 0; i < n; i++) { stack.push(scanner.nextInt()); } // Convert Stack to array using toArray method Integer[] array = stack.toArray(new Integer[0]); System.out.println("Array elements:"); for (Integer element : array) { System.out.print(element + " "); } scanner.close(); } }
Output:
Enter the size of the stack: 4 Enter the elements: 25 14 8 90 Array elements : 25 14 8 90
Explanation:
The toArray() method in Java’s Stack class converts the elements of the stack into an array .It returns an array containing all elements in the same order as they are in the stack.
Leave a Reply