How to add all elements of a list to ArrayList

In this post we will learn how to add all list elements to ArrayList in Java . We will use addAll()  method of arraylist class.

Sysntax :

public boolean addAll(Collection<? extends E> c) {


}
  • This method appends all of the elements in the given collection to the end of this list, in the order that they are returned by the specified collection’s iterator (optional operation). The behavior of this operation is undefined if the specified collection  is modified while the operation is in progress. (Note that this will occur if the specified collection is this list, and it’s nonempty.)
  • This method take collection c as parameter.
  • This method returns true if this list changed as a result of the call
  • It throws UnsupportedOperationException if the addAll operation is not supported by this list
  • ClassCastException – if the class of an element of the specified collection prevents it from being added  to this list
  • NullPointerException – if the specified collection contains one or more null elements and this list does not permit null elements, or if the specified collection is null
  • IllegalArgumentException – if some property of an element of the specified collection prevents it from being added to this list
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class AddAllElement {

public static void main(String[] args) {

ArrayList<String> arr = new ArrayList<String>();

// add element in arraylist
arr.add("c");
arr.add("php");
arr.add("html");
arr.add("java");

// print arraylist
System.out.println("arrayList is = " + arr);

List<String> brr = new ArrayList<String>();
brr.add("one");
brr.add("second");

//Appends all of the elements in the specified collection
//to the end of this list, in the order that they are
//returned by the specified collection's Iterator.
arr.addAll(brr);

System.out.println("After AddAll list brr ="+arr);

List<String> linkList = new LinkedList<String>();
linkList.add("Delhi");
linkList.add("Kurukshetra");

arr.addAll(linkList);

System.out.println("After AddAll list linklist"+arr);
}

}

Output:

arrayList is = [c, php, html, java]

After AddAll list brr =[c, php, html, java, one, second]

After AddAll list linklist[c, php, html, java, one, second, Delhi, Kurukshetra]

 

Leave a Reply

Your email address will not be published. Required fields are marked *

− 3 = 5