In this tutorial we will see how to copy and add all the elements of a list to ArrayList. In order to do that we will be using addAll method
of ArrayList class.
public boolean addAll(Collection c)
It adds all the elements of specified Collection
c to the end of the calling list. It throws NullPointerException if the specified Collection
is null.
Complete Example of Copying List elements to ArrayList
package beginnersbook.com; 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 lements 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]
addAll() method is not throwing nullpointerException.if the list is empty
@ 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