In this tutorial we will see the usage of addAll()
method of java.util.ArrayList class
. This method is used for adding all the elements of a list to the another list.
public boolean addAll(Collection c)
It adds all the elements of specified Collection c to the current list.
Example
In this example we are adding all the elements of an arraylist to another arraylist by using addAll() method.
package beginnersbook.com; import java.util.ArrayList; public class ExampleOfaddAll { public static void main(String[] args) { // ArrayList1 of String type ArrayList<String> al = new ArrayList<String>(); al.add("Hi"); al.add("hello"); al.add("String"); al.add("Test"); System.out.println("ArrayList1 before addAll:"+al); //ArrayList2 of String Type ArrayList<String> al2 = new ArrayList<String>(); al2.add("Text1"); al2.add("Text2"); al2.add("Text3"); al2.add("Text4"); //Adding ArrayList2 into ArrayList1 al.addAll(al2); System.out.println("ArrayList1 after addAll:"+al); } }
Output:
ArrayList1 before addAll:[Hi, hello, String, Test] ArrayList1 after addAll:[Hi, hello, String, Test, Text1, Text2, Text3, Text4]
Reference:
http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html#addAll(java.util.Collection)
Leave a Reply