Java LinkedList addAll(Collection c) Method Example

The addAll(Collection c) method of java.util.LinkedList class will simply inserts all of the elements in the specified collection to the end of this list.

Signature

public boolean addAll(Collection c)

This method appends all the elements of a collection at the end of the list and will throw “NullPointerException” when the specified collection is null.

Example

The following example shows the usage of LinkedList.addAll(c) method.

import java.util.LinkedList;

public class AddAllMethodLinkedListExample {
	public static void main(String args[])
	{
	// Create LinkedList l1 object
        LinkedList l1 = new LinkedList();
        
        //adding elements to l1
        l1.add("String 1");
        l1.add("String 2");
        l1.add("String 3");
        l1.add("String 4");
        
        System.out.println("**Elements of l1 before adding**");
        for(String val: l1)
        {
        	System.out.println(val);
        }

        // Create LinkedList l2 object
        LinkedList l2 = new LinkedList();
        
        //adding elements to l2
        l2.add("Element 1");
        l2.add("Element 2");
        l2.add("Element 3");
        l2.add("Element 4");

        //Adding l2 to l1
        l1.addAll(l2);

        System.out.println("**Elements of l1 after adding**");
        for(String val: l1)
        {
        	System.out.println(val);
        }
	}
}

Output

**Elements of al1 before adding**
String 1
String 2
String 3
String 4
**Elements of al1 after adding**
String 1
String 2
String 3
String 4
Element 1
Element 2
Element 3
Element 4

Leave a Reply

Your email address will not be published. Required fields are marked *