How List.add() and List.addAll() works?

UPDATED: 18 November 2014
Java Collections

We will understand various cases for adding elements in List. I created graphics that will help you to understand the behind the scene.

List.add(E e)
This will add element in List from 0th position to nth position based on last index of List.



List.add(int index, E element)
This will add element in List at the specified index. If there exists any element at the specified position then It'll shift down all the elements from specified position and add new element at the given position.



List.addAll(Collection c)
This will add another list at the end of current list.



List.addAll(int index, Collection c)
This will add another List at the specified index. If there exists any element at the specified position then It'll shift down all the elements from specified position and add new elements from the given position.



Source Code
import java.util.ArrayList;
import java.util.List;

/**
 * @author javaQuery
 */
public class AddListExample {

    public static void main(String[] args) {
        /* Create list of String */
        List listString = new ArrayList();
        /* Add element from 0th position */
        listString.add("a");
        listString.add("c");
        listString.add("d");

        /* Print list */
        System.out.println("Initial List:\n" + listString);
        System.out.println("---------------------------------");

        /* Add element at 1st position */
        listString.add(1, "b");
        System.out.println("List after add(int index, E element):\n" + listString);
        System.out.println("---------------------------------");

        /* Create another list of String */
        List addAllListBeginning = new ArrayList();
        /* Add element in list */
        addAllListBeginning.add("e");
        addAllListBeginning.add("f");

        /* Add `addAllListBeginning` at the end of `listString` */
        listString.addAll(addAllListBeginning);

        /* Print list */
        System.out.println("List after addAll(Collection c):\n" + listString);
        System.out.println("---------------------------------");

        /* Create another list of String */
        List addAllListAtIndex = new ArrayList();
        /* Add element in list */
        addAllListAtIndex.add("x");
        addAllListAtIndex.add("y");
        addAllListAtIndex.add("z");

        /* Add `addAllListAtIndex` at the specified index */
        listString.addAll(2, addAllListAtIndex);
        System.out.println("List after addAll(int index, Collection c):\n" + listString);
    }
}

Output
Initial List:
[a, c, d]
---------------------------------
List after add(int index, E element):
[a, b, c, d]
---------------------------------
List after addAll(Collection c):
[a, b, c, d, e, f]
---------------------------------
List after addAll(int index, Collection c):
[a, b, x, y, z, c, d, e, f]

0 comments :