Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Java Program to Copy Elements of ArrayList to Vector

  • Last Updated : 07 Jan, 2021

Vector implements List Interface, like ArrayList it also maintains insertion order but it is rarely used in the non-thread environment as it is synchronized, and due to which it gives a poor performance in adding, searching, deleting, and updating of its elements. To copy elements from one collection to others, pass the object of ArrayList to the constructor of Vector while in initialization or copy element-wise using iteration.

Approach 1:

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

Vector<Integer> vector = new Vector<>(arrayList);
  1. Create a Vector object and while initialization passes the object of ArrayList in the constructor.
  2. Print the Vector.

Below is the implementation of the above approach:

Java




// Copy Elements of ArrayList to 
// Java Vector using Constructor
import java.util.*;
class GFG {
    public static void main(String[] args)
    {
        // create a list of string
        ArrayList<String> L = new ArrayList<String>();
  
        // add elements
        L.add("Rohan");
        L.add("Sangeeta");
        L.add("Ritik");
        L.add("Yogesh");
  
        // create a vector and pass Object
        // ArrayList into the constructor
        Vector<String> V = new Vector<String>(L);
  
        // print vector
        System.out.println(V);
    }
}
Output



[Rohan, Sangeeta, Ritik, Yogesh]

Time Complexity: O(n), where n is the size of ArrayList.

Approach 2:

  1. Create a Vector.
  2. Start iterating the ArrayList.
  3. Add each element of ArrayList into the Vector.
  4. After completion of iteration, print the Vector.

Below is the implementation of the above approach:

Java




// Copy Elements of ArrayList to
// Java Vector by iteration and adding
// each element to the vector
import java.util.*;
class GFG {
    public static void main(String[] args)
    {
        // create a list of string
        ArrayList<String> L = new ArrayList<String>();
  
        // add elements
        L.add("Rohan");
        L.add("Sangeeta");
        L.add("Ritik");
        L.add("Yogesh");
  
        // create a vector
        Vector<String> V = new Vector<String>();
  
        for (String s : L)
            V.add(s);
  
        // print vector
        System.out.println(V);
    }
}
Output
[Rohan, Sangeeta, Ritik, Yogesh]

Time Complexity: O(n), where n is the size of ArrayList.




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!