Java Stack - addAll() Method
The java.util.Stack.addAll() method is used to append all elements of the specified collection at the top of the stack. The order of the appended element will be the same as returned by the specified collection's Iterator. This method should not be called while the specified collection is modified. This may cause undefined behavior and return wrong result.
Syntax
public boolean addAll(Collection<? extends E> c)
Here, E is the type of element maintained by the container.
Parameters
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 NullPointerException, if the specified collection is null.
Example:
In the example below, the java.util.Stack.addAll() method is used to append all elements of the stack stk at the top of 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(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, 20, 30, 100, 200]
❮ Java.util - Stack