Skip to Content

Copy Elements of ArrayList to Java Vector Example

  1. /*
  2.   Copy Elements of ArrayList to Java Vector Example
  3.   This java example shows how to copy elements of Java ArrayList to Java Vector using
  4.   copy method of Collections class.
  5. */
  6.  
  7. import java.util.ArrayList;
  8. import java.util.Collections;
  9. import java.util.Vector;
  10.  
  11. public class CopyElementsOfArrayListToVectorExample {
  12.  
  13.   public static void main(String[] args) {
  14.     //create an ArrayList object
  15.     ArrayList arrayList = new ArrayList();
  16.    
  17.     //Add elements to Arraylist
  18.     arrayList.add("1");
  19.     arrayList.add("4");
  20.     arrayList.add("2");
  21.     arrayList.add("5");
  22.     arrayList.add("3");
  23.    
  24.     //create a Vector object
  25.     Vector v = new Vector();
  26.    
  27.     //Add elements to Vector
  28.     v.add("A");
  29.     v.add("B");
  30.     v.add("D");
  31.     v.add("E");
  32.     v.add("F");
  33.     v.add("G");
  34.     v.add("H");
  35.    
  36.     /*
  37.       To copy elements of Java ArrayList to Java Vector use,
  38.       static void copy(List dstList, List sourceList) method of Collections class.
  39.      
  40.       This method copies all elements of source list to destination list. After copy
  41.       index of the elements in both source and destination lists would be identical.
  42.      
  43.       The destination list must be long enough to hold all copied elements. If it is
  44.       longer than that, the rest of the destination list's elments would remain
  45.       unaffected.    
  46.     */
  47.    
  48.     System.out.println("Before copy, Vector Contains : " + v);
  49.    
  50.     //copy all elements of ArrayList to Vector using copy method of Collections class
  51.     Collections.copy(v,arrayList);
  52.    
  53.     /*
  54.        Please note that, If Vector is not long enough to hold all elements of
  55.        ArrayList, it throws IndexOutOfBoundsException.
  56.     */
  57.    
  58.     System.out.println("After Copy, Vector Contains : " + v);  
  59.   }
  60. }
  61.  
  62. /*
  63. Output would be
  64. Before copy Vector Contains : [A, B, D, E, F, G, H]
  65. After Copy Vector Contains : [1, 4, 2, 5, 3, G, H]
  66. */