Skip to Content

Copy Elements of One Java Vector to Another Java Vector Example

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