Skip to Content

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

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