Stack addAll(int, Collection) method in Java with Example
Last Updated :
24 Dec, 2018
The
addAll(int, Collection) method of
Stack Class is used to append all of the elements from the collection passed as a parameter to this function at a specific index or position of a Stack.
Syntax:
boolean addAll(int index, Collection C)
Parameters: This function accepts two parameters as shown in the above syntax and are described below.
- index: This parameter is of integer datatype and specifies the position in the Stack starting from where the elements from the container will be inserted.
- C: It is a collection of ArrayList. It is the collection whose elements are needed to be appended.
Return Value: The method returns
True if at least one action of append is performed, else
False.
Below program illustrate the Java.util.Stack.addAll() method:
Example 1:
Java
// Java code to illustrate boolean addAll()
import java.util.*;
import java.util.ArrayList;
public class GFG {
public static void main(String args[])
{
// Creating an empty Stack
Stack<String> stack = new Stack<String>();
// Use add() method to add elements in the Stack
stack.add("Geeks");
stack.add("for");
stack.add("Geeks");
stack.add("10");
stack.add("20");
// A collection is created
Collection<String> c = new ArrayList<String>();
c.add("A");
c.add("Computer");
c.add("Portal");
c.add("for");
c.add("Geeks");
// Displaying the Stack
System.out.println("The Stack is: " + stack);
// Appending the collection to the Stack
stack.addAll(1, c);
// Clearing the Stack using clear() and displaying
System.out.println("The new Stack is: " + stack);
}
}
Output:
The Stack is: [Geeks, for, Geeks, 10, 20]
The new Stack is: [Geeks, A, Computer, Portal, for, Geeks, for, Geeks, 10, 20]
Example 2:
Java
// Java code to illustrate
// boolean add(Object element)
import java.util.*;
public class StackDemo {
public static void main(String args[])
{
// Creating an empty Stack
Stack<Integer> stack
= new Stack<Integer>();
// Use add() method
// to add elements in the Stack
stack.add(10);
stack.add(20);
stack.add(30);
stack.add(40);
stack.add(50);
// A collection is created
Collection<Integer> c = new ArrayList<Integer>();
c.add(1);
c.add(2);
c.add(3);
// Displaying the Stack
System.out.println("The Stack is: " + stack);
// Appending the collection to the Stack
stack.addAll(2, c);
// Clearing the Stack using clear() and displaying
System.out.println("The new Stack is: " + stack);
}
}
Output:
The Stack is: [10, 20, 30, 40, 50]
The new Stack is: [10, 20, 1, 2, 3, 30, 40, 50]
Explore
Java Basics
OOP & Interfaces
Collections
Exception Handling
Java Advanced
Practice Java