addAll ArrayList Java

Java ArrayList addAll[int index, Collection c] Method example

By Chaitanya Singh | Filed Under: Java Collections

In the last tutorial we have shared the example ofaddAll[Collection c] method which is used for adding all the elements of Collection c at the end of list. Here we will see another variant add[int index, Collection c]which adds all the elements of c at the specified index of a list.

public boolean addAll[int index, Collection c]

Example

In this example we have two ArrayList of String type and we are adding the element of second arraylist at the 3rd position[index =2] of first arraylist.

package beginnersbook.com; import java.util.ArrayList; public class ExampleOfaddAllMethod { public static void main[String[] args] { // ArrayList1 ArrayList al = new ArrayList[]; al.add["Apple"]; al.add["Orange"]; al.add["Grapes"]; al.add["Mango"]; System.out.println["ArrayList1 before addAll:"+al]; //ArrayList2 ArrayList al2 = new ArrayList[]; al2.add["Fig"]; al2.add["Pear"]; al2.add["Banana"]; al2.add["Guava"]; System.out.println["ArrayList2 content:"+al2]; //Adding ArrayList2 in ArrayList1 at 3rd position[index =2] al.addAll[2, al2]; System.out.println["ArrayList1 after adding ArrayList2 at 3rd Pos:\n"+al]; } }

Output:

ArrayList1 before addAll:[Apple, Orange, Grapes, Mango] ArrayList2 content:[Fig, Pear, Banana, Guava] ArrayList1 after adding ArrayList2 at 3rd Pos: [Apple, Orange, Fig, Pear, Banana, Guava, Grapes, Mango]

Reference:

//docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html#addAll[int, java.util.Collection]

Video liên quan

Chủ Đề