Java LinkedList addAll(int index,Collection C) Method Example

The addAll(int index,Collection c) method of java.util.LinkedList class will inserts all the element of the collection from the position mentioned as index.

Signature

public boolean addAll(int index,Collection c)

Inserts all of the elements in the specified collection into this list, starting at the specified position and will throw “NullPointerException” when the specified collection is null and IndexOutOfBoundsException when the index is out of range.

Example

The following example shows the usage of addAll(index,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 contents at the index 2 of l1
        l1.addAll(2,l2);

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

Output

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

Leave a Reply

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