The ArrayList.addAll(collection) appends all of the elements of argument Collection into the current List at the end. The order of appended elements is same as they are returned by the argument collection’s Iterator. To add a single item to the list, use add().
Please note that we can add elements of any type in ArrayList, but make the application code more predictable, we should add elements of a certain type only using generics for compile-time type safety.
1. ArrayList.addAll() API
The addAll() method first ensures that there is sufficient space in the list. If the list does not have space, then it grows the list by adding more spaces in the underlying array. Then addAll() appends new elements to the end of the list or at the specified index position.
public boolean addAll(Collection<? extends E> c);
public boolean addAll(int fromIndex, Collection<? extends E> c);
- Method arguments – a Collection containing elements to be added to this list. when the fromIndex argument is present, the collection items are inserted at the specified index position.
- Method returns – true if this list changed as a result.
- Method throws – NullPointerException if the specified collection is null.
2. ArrayList.addAll() Example
We have the following list instances containing alphabets.
ArrayList<String> list1 = new ArrayList<>(); //list 1
list1.add("A");
list1.add("B");
list1.add("C");
list1.add("D");
ArrayList<String> list2 = new ArrayList<>(); //list 2
list2.add("E");
2.1. Appending Items to the End of List
The following Java program adds the elements of another list to the current arraylist using addAll(). We are declaring generic list types to ensure type safety in runtime.
list1.addAll(list2);
System.out.println(list1); //combined list
Program output.
[A, B, C, D, E]
2.2. Appending Items at the Specified Position
Let us pass the'fromIndex'
at which location the method will insert the elements from the specified collection. We are inserting the string “E” at the index position 2, i.e. into the middle of the current list.
list1.addAll(2, list2);
System.out.println(list1); //combined list
Program output.
[A, B, E, F, C, D]
Happy Learning !!
Read More: ArrayList Java Docs