Open In App

Copy Elements of Vector to Java ArrayList

Since Vector class and ArrayList class both are part of Java Collections, ie Collection framework, so both of these classes can use methods available to the Collection framework. Copy() method is one of the methods of Collection Interface which is used to copy one list to another list, here list can be any collection like ArrayList, LinkedList, and Vector.

One important point to remember is that if the destination list length is greater than the length of the source list that is to copy, then the other element will remain unaffected, ie if the length of the destination list is 4 and the length of the source list is 3, then 3 elements of destination list would be replaced by elements of source list, but the 4th element, ie at index 3 would remain unaffected in the destination list.



Ways To copy elements of the Vector to ArrayList

  1. Passing in the constructor
  2. Adding one by one using add() method

Method 1: Passing in the constructor 






// Java Program for copying Vector to List
// by passing in the constructor
 
import java.io.*;
import java.util.*;
 
class GFG {
    public static void main(String[] args)
    {
 
        // creation of Vector of Integers
        Vector<Integer> gfg = new Vector<>();
 
        // adding elements to first Vector
        gfg.add(11);
        gfg.add(22);
        gfg.add(24);
        gfg.add(39);
 
        // passing in the constructor of List
        List<Integer> gfg2 = new ArrayList<>(gfg);
 
        // Iterating over second Vector
        System.out.println(
            "-----Iterating over the List----");
 
        for (Integer value : gfg2) {
            System.out.println(value);
        }
    }
}

Output
-----Iterating over the List----
11
22
24
39

Method 2: Adding one by one using add() method  




// Java Program for copying one Vector to the List
// by adding elements one by one using add() method
 
import java.io.*;
import java.util.*;
 
class GFG {
    public static void main(String[] args)
    {
 
        // creation of Vector of Integers
        Vector<Integer> gfg = new Vector<>();
 
        // adding elements to first Vector
        gfg.add(50);
        gfg.add(24);
        gfg.add(95);
        gfg.add(31);
 
        List<Integer> gfg2 = new ArrayList<>();
 
        for (Integer value : gfg) {
            gfg2.add(value);
        }
 
        // Iterating over List
        System.out.println(
            "-----Iterating over the List----");
 
        for (Integer value : gfg2) {
            System.out.println(value);
        }
    }
}

Output
-----Iterating over the List----
50
24
95
31

Article Tags :