Java LinkedList - addAll() Method
The java.util.LinkedList.addAll() method is used to insert all elements of the specified collection at the specified position in the list. The method shifts the current element at the specified position (if any) and any subsequent elements to the right (increases their indices). The new elements will appear in the list 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 list. |
c |
Specify the collection containing all elements which need to be added in the list. |
Return Value
Returns true if the list changed as a result of the call, else returns false.
Exception
Throws IndexOutOfBoundsException, if the index is out of range i.e., (index < 0 || index > size()).
Throws NullPointerException, if the specified collection is null.
Example:
In the example below, the java.util.LinkedList.addAll() method is used to insert all elements of the LinkedList list at the specified position in the LinkedList MyList.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a linkedlist LinkedList<Integer> MyList = new LinkedList<Integer>(); LinkedList<Integer> list = new LinkedList<Integer>(); //populating MyList MyList.add(10); MyList.add(20); MyList.add(30); //populating list list.add(100); list.add(200); //printing linkedlist System.out.println("Before method call, MyList contains: " + MyList); MyList.addAll(1, list); //printing linkedlist System.out.println("After method call, MyList contains: " + MyList); } }
The output of the above code will be:
Before method call, MyList contains: [10, 20, 30] After method call, MyList contains: [10, 100, 200, 20, 30]
❮ Java.util - LinkedList