Java Utility Library

Java Stack - addAll() Method



The java.util.Stack.addAll() method is used to insert all elements of the specified collection at the specified position in the stack. The method shifts the current element at the specified position (if any) and any subsequent elements to the up (increases their indices). The new elements will appear in the stack in the order that they are returned by the specified collection's iterator.

Syntax

public boolean addAll(int index, Collection<? extends E> c)

Here, E is the type of element maintained by the container.


Parameters

index Specify index number at which the first element of collection need to be inserted in the stack.
c Specify the collection containing all elements which need to be added in the stack.

Return Value

Returns true if the stack changed as a result of the call, else returns false.

Exception

Throws IndexOutOfBoundsException, if the index is out of range.

Throws NullPointerException, if the specified collection is null.

Example:

In the example below, the java.util.Stack.addAll() method is used to insert all elements of the stack stk at the specified position in the stack MyStack.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a stack
    Stack<Integer> MyStack = new Stack<Integer>();
    Stack<Integer> stk = new Stack<Integer>();

    //populating MyStack 
    MyStack.push(10);
    MyStack.push(20);
    MyStack.push(30);

    //populating stk 
    stk.push(100);
    stk.push(200);

    //printing stack
    System.out.println("Before method call, MyStack contains: " + MyStack); 

    MyStack.addAll(1, stk);
    
    //printing stack
    System.out.println("After method call, MyStack contains: " + MyStack);      
  }
}

The output of the above code will be:

Before method call, MyStack contains: [10, 20, 30]
After method call, MyStack contains: [10, 100, 200, 20, 30]

❮ Java.util - Stack