Skip to Content

Insert all elements of other Collection to Specified Index of Java ArrayList Example

  1. /*
  2.   Insert all elements of other Collection to Specified Index of Java
  3.   ArrayList Example
  4.   This Java Example shows how to insert all elements of other Collection object
  5.   at specified index of Java ArrayList object using addAll method.
  6. */
  7.  
  8. import java.util.ArrayList;
  9. import java.util.Vector;
  10.  
  11. public class InsertAllElementsOfOtherCollectionToArrayListExample {
  12.  
  13.   public static void main(String[] args) {
  14.  
  15.     //create an ArrayList object
  16.     ArrayList arrayList = new ArrayList();
  17.    
  18.     //Add elements to Arraylist
  19.     arrayList.add("1");
  20.     arrayList.add("2");
  21.     arrayList.add("3");
  22.    
  23.     //create a new Vector object
  24.     Vector v = new Vector();
  25.     v.add("4");
  26.     v.add("5");
  27.    
  28.     /*
  29.       To insert all elements of another Collection to sepcified index of ArrayList
  30.       use
  31.       boolean addAll(int index, Collection c) method.
  32.       It returns true if the ArrayList was changed by the method call.
  33.     */
  34.    
  35.     //insert all elements of Vector to ArrayList at index 1
  36.     arrayList.addAll(1,v);
  37.    
  38.     //display elements of ArrayList
  39.     System.out.println("After inserting all elements of Vector at index 1,
  40.                                                    ArrayList contains..");
  41.     for(int i=0; i<arrayList.size(); i++)
  42.       System.out.println(arrayList.get(i));
  43.  
  44.   }
  45. }
  46.  
  47. /*
  48. Output would be
  49. After inserting all elements of Vector at index 1, ArrayList contains..
  50. 1
  51. 4
  52. 5
  53. 2
  54. 3
  55. */

Advertisement: