Java Utility Library

Java LinkedList - addAll() Method



The java.util.LinkedList.addAll() method is used to append all elements of the specified collection at the end of the list. 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 list.

Return Value

Returns true if the list 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.LinkedList.addAll() method is used to append all elements of the LinkedList list at the end of 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(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, 20, 30, 100, 200]

❮ Java.util - LinkedList