Write a Java program to add an ArrayList into Stack collection
The code demonstrates how to add elements from an ArrayList to a Stack in Java. Let's go through the code step by step:
- The code begins with the import statements import java.io.*; and import java.util.*; , which import the necessary classes from the java.io and java.util packages.
- The Add_ArrayList class is defined, serving as the entry point of the program.
- In the main method, a Stack<Integer> object named stack_list is created using generics to specify that it will contain integers.
- Five integer values (10, 20, 30, 40, and 50) are pushed onto the stack_list using the push method.
- The current state of the stack_list is printed using the System.out.println statement, concatenating the string "The Stack is: " with the value of stack_list.
- An ArrayList<Integer> object named array_List is created using generics to specify that it will contain integers.
- Five integer values (60, 70, 80, 90, and 100) are added to the array_List using the add method.
- The addAll method of the stack_list is called, passing array_List as an argument. This method adds all the elements from array_List to stack_list.
- The current state of the stack_list is printed again using the System.out.println statement.
Source Code
import java.io.*;
import java.util.*;
public class Add_ArrayList
{
public static void main(String[] args)
{
Stack < Integer > stack_list = new Stack < Integer > ();
stack_list.push(10);
stack_list.push(20);
stack_list.push(30);
stack_list.push(40);
stack_list.push(50);
System.out.println("The Stack is : " + stack_list);
ArrayList < Integer > array_List = new ArrayList < Integer > ();
array_List.add(60);
array_List.add(70);
array_List.add(80);
array_List.add(90);
array_List.add(100);
stack_list.addAll(array_List);
System.out.println("The Stack is : " + stack_list);
}
}
Output
The Stack is : [10, 20, 30, 40, 50]
The Stack is : [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]