Java Collection How to - Insert all elements of other Collection to Specified Index of ArrayList








Question

We would like to know how to insert all elements of other Collection to Specified Index of ArrayList.

Answer

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
//  ww  w .j a v  a  2  s .  com
public class Main {
  public static void main(String[] args) {
    List<String> arrayList = new ArrayList<String>();
    arrayList.add("1");
    arrayList.add("2");
    arrayList.add("3");

    Vector<String> v = new Vector<String>();
    v.add("4");
    v.add("5");

    // insert all elements of Vector to ArrayList at index 1
    arrayList.addAll(1, v);
    
    for (String str: arrayList)
      System.out.println(str);
  }
}

The code above generates the following result.