In this tutorial, we will write a java program to copy elements of one ArrayList to another ArrayList in Java. We will be using addAll() method of ArrayList class to do that.
public boolean addAll(Collection c)
When we call this method like this:
newList.addAll(oldList);
It appends all the elements of oldList
to the newList
. It throws NullPointerException
, if oldList
is null.
Note: This method doesn’t clone the ArrayList, instead it appends the elements of one ArrayList to another ArrayList.
Copy elements from one ArrayList to another ArrayList
In the following example, we have an ArrayList al
that contains three elements. We have another List list
that contains some elements, we are copying the elements of list
to the al
. This is done using addAll()
method, which copies the elements of one List to another another list. This operation doesn’t remove the existing elements of the list, in which the elements are copied.
import java.util.ArrayList; import java.util.List; public class ListToArrayListExample { public static void main(String a[]){ ArrayList<String> al = new ArrayList<String>(); //Adding elements to the ArrayList al.add("Text 1"); al.add("Text 2"); al.add("Text 3"); System.out.println("ArrayList Elements are: "+al); //Adding elements to a List List<String> list = new ArrayList<String>(); list.add("Text 4"); list.add("Text 5"); list.add("Text 6"); //Adding all elements of list to ArrayList using addAll al.addAll(list); System.out.println("Updated ArrayList Elements: "+al); } }
Output:
ArrayList Elements are: [Text 1, Text 2, Text 3] Updated ArrayList Elements: [Text 1, Text 2, Text 3, Text 4, Text 5, Text 6]
Recommended Articles:
himanhsu sharma says
addAll() method is not throwing nullpointerException.if the list is empty
Anvesh says
@ Himanshu,
ArrayList never be a null, instead it is an empty when u create. if you want more clarity, execute the below code.
List list = new ArrayList();
List newList = new ArrayList();
list.addAll(newList);
System.out.println(list); // this works fine and creates a list with empty
List list = null;
List newList = null;
list.addAll(newList);
System.out.println(list); // this will give you NPE. since List is not initiated with any of its implemented class