Write a Java program to convert a Stack collection into an Object array


The code demonstrates how to convert a stack into an array in Java using the toArray method. Let's break down the code:

  • The code starts by importing the necessary libraries: java.io.* and java.util.* .
  • The Stack_ObjectArray class is defined, serving as the entry point of the program.
  • In the main method, a new stack object named stack_list is created using the raw Stack class. Again, it is recommended to use generics to provide type safety.
  • Several strings, namely "Pink," "Yellow," "Blue," "Green," and "Red," are pushed onto the stack using the push method.
  • The toArray method is used to convert stack_list into an array. The resulting array is assigned to the arr variable, which is of type Object[] since the toArray method returns an array of objects.
  • The System.out.println statement is used to print the contents of the stack by concatenating the stack with the string "Stack Elements : " using the + operator.
  • Another System.out.println statement is used to print the elements of the array by iterating over it using a for-each loop. Each element is printed on a separate line.

Source Code

import java.io.*;
import java.util.*;
public class Stack_ObjectArray
{
	public static void main(String[] args) 
	{
		Stack stack_list = new Stack();
		stack_list.push("Pink");
		stack_list.push("Yellow");
		stack_list.push("Blue");
		stack_list.push("Green");
		stack_list.push("Red");
 
		Object[] arr = stack_list.toArray();
 
		System.out.println("Stack Elements : " + stack_list);
		System.out.println("Array Elements :");
		for(Object item : arr)
		{
			System.out.println(item+" ");			
		}
	}
}

Output

Stack Elements : [Pink, Yellow, Blue, Green, Red]
Array Elements :
Pink
Yellow
Blue
Green
Red