Skip to Content

Copy Elements of Vector to Java ArrayList Example

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