beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

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 of addAll(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<String> al = new ArrayList<String>();
       al.add("Apple");
       al.add("Orange");
       al.add("Grapes");
       al.add("Mango");
       System.out.println("ArrayList1 before addAll:"+al);

       //ArrayList2 
       ArrayList<String> al2 = new ArrayList<String>();
       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:

http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html#addAll(int, java.util.Collection)

Enjoyed this post? Try these related posts

  1. Java ArrayList addAll(Collection c) Method example
  2. How to loop ArrayList in Java
  3. ArrayList in java with example programs – Collections Framework
  4. Java – Check if a particular value exists in HashMap example
  5. Vector ListIterator example in Java
  6. Java ArrayList of Object Sort Example (Comparable And Comparator)

Leave a Reply Cancel reply

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

ArrayList Tutorial

  • Java ArrayList

Java ArrayList Methods

  • add(Object obj)
  • add(int index, Object element)
  • addAll(Collection c)
  • addAll(int index, Collection c)
  • contains()
  • get()
  • indexOf()
  • ensureCapacity()
  • isEmpty()
  • lastIndexOf()
  • remove()
  • remove(Object obj)
  • trimToSize()
  • set()
  • clone()
  • clear()
  • size()

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap