In this tutorial, we are going to discuss how to convert stack to an array in java. First of all, we need to understand what is a stack and Array ?
Stack can be stated as the type of a linear data structure which works on the principle of the LIFO. LIFO stands for Last In First Out. In the stack, the new element can be added from the one side only. The side from which the insertion and the deletion of the element happen is referred to as TOP of the stack.
For add or insert a new element we use (push) operation.
For remove we use (pop) operation.
An array in programming is a sequential collection of items of the same type stored in contiguous memory locations, allowing easy access to elements by calculating their positions relative to the start of the array.
Let’s understand the java code demonstrates the use of a Stack data structure and the method to convert a Stack into an array.
Convert stack to an array in java
Import Necessary packages which imports all classes including (Stack) which is used in the program.
import java.utill.*
Defining the Class name and implement Main method.
public class StackToArray { public static void main(String args[]) {
Creating an Empty Stack (” Stack “object that can hold “String ” elements.
Stack<String> stack = new Stack <String>();
Adding Elements to Stack in which we use we push() method.
stack.push("CodeSpeedy"); stack.push("a better"); stack.push("way to learn");
For converting Stack to Array we use ” toArray() ” method is used to converting the “stack” into an array.
Object[] arr = stack.toArray();
For displaying each element of the array we applying “for” loop.
System.out.println("After converting stack to array : "); for (Object obj : array) { System.out.println(obj);
Notes-your program mussed be closed by brace[ “}” ]
CODE –
import java.util.*; public class StackToArray { public static void main(String args[]) { Stack<String> stack = new Stack<>(); stack.push("CodeSpeedy"); stack.push("a better"); stack.push("way to learn"); Object[] array = stack.toArray(); System.out.println("After converting stack to array :"); for (Object obj : array) { System.out.println(obj); } } }
Output: CodeSpeedy a better way to learn