Addall Method in Java

How addAll(int index, Collection c) Works in a Java ArrayList

With the overloaded addAll(int index, Collection c) method, you can place all elements of a supplied collection into an ArrayList at a position you choose. The call returns a boolean, and any elements already at or after that index are shifted forward.

Signature of the Method

boolean addAll(int index, Collection c);

  • index — the spot at which the new elements are placed.
  • c — the collection providing the elements to be added.
  • Return type — a boolean that reports the result.
  • Exception — a NullPointerException occurs if the collection passed in is null.

A Practical Example

In the example below, a list of names is created, a second list is built, and that second list is inserted into the first at index 1. The elements that follow move along to free up space.

import java.util.ArrayList;

public class ArraylistExample {
  public static void main(String[] args) {
    ArrayList<String> listOfNames = new ArrayList<String>();
    listOfNames.add("JAVA");
    listOfNames.add("GOAL");
    listOfNames.add("RAVI");

    ArrayList<String> listOfNames2 = new ArrayList<String>();
    listOfNames2.add("NEW");
    listOfNames2.add("LIST");

    listOfNames.addAll(1, listOfNames2);

    for (String name : listOfNames) {
      System.out.println("Names from list = " + name);
    }
  }
}

Result

Names from list = JAVA
Names from list = NEW
Names from list = LIST
Names from list = GOAL
Names from list = RAVI

See more options on the Java ArrayList methods page, or jump back to the article discussion.

Explore Java Topics

Visit the JavaGoal category for a guided learning path that takes you through Java from the fundamentals up to advanced features.

Keep in Touch

Talk to us in chat, follow our Facebook page, or subscribe to our social channels to get new Java tutorials and videos.

Chat Now Facebook

When you insert at an index, the ArrayList keeps the order of the incoming collection and moves the existing elements to the right. If the index is out of range, the call fails with an IndexOutOfBoundsException, so it is worth checking the position before you add.