Write a Java program to add a Stack collection into another Stack collection
The code demonstrates how to add elements from one stack to another stack in Java using the addAll method. Let's break down the code:
- The code starts by importing the necessary libraries: java.io.* and java.util.*.
- The AddStack 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 generics. It is specified that the stack will contain elements of type Integer.
- Several integers, from 10 to 50 in increments of 10, are pushed onto the stack_list using the push method.
- The System.out.println statement is used to print the string "The Stack is: " followed by the contents of stack_list using the + operator.
- Another stack object named sta is created using generics, also specified to contain elements of type Integer.
- Several integers, from 60 to 100 in increments of 10, are added to the sta stack using the add method.
- The addAll method is used to add all the elements from sta to stack_list.
- The System.out.println statement is used to print the string "The Stack is: " followed by the updated contents of stack_list using the + operator.
Source Code
import java.io.*;
import java.util.*;
public class AddStack
{
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);
Stack < Integer > sta = new Stack < Integer > ();
sta.add(60);
sta.add(70);
sta.add(80);
sta.add(90);
sta.add(100);
stack_list.addAll(sta);
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]