Convert Vector to ArrayList in Java
Last Updated :
08 Sep, 2022
Improve
There are multiple ways to convert vector to ArrayList, using passing the Vector in ArrayList constructor and by using simple vector traversal and adding values to ArrayList.
Approach 1:
- Create a Vector.
- Add some values in Vector.
- Create a new ArrayList.
- Traverse vector from the left side to the right side.
- Start adding each element in ArrayList.
Below is the implementation of the above approach:
// Convert Vector to ArrayList in Java
import java.util.Vector;
import java.util.ArrayList;
public class GFG {
public static void main(String[] args)
{
// Create a Vector that contain strings
Vector<String> v = new Vector<String>();
// add values in vector
v.add("a");
v.add("b");
v.add("c");
v.add("d");
v.add("e");
// Display the Vector
System.out.println(" Vector : " + v);
ArrayList<String> Arrlist = new ArrayList<String>();
// Convert Vector to ArrayList
for (int i = 0; i < v.size(); i++)
Arrlist.add(v.get(i));
// Display ArrayList
System.out.println("\n ArrayList : " + Arrlist);
}
}
Time Complexity: O(n)
Approach 2:
- Create a Vector.
- Add some values in Vector.
- Create an ArrayList and pass the Vector in ArrayList Constructor.
Syntax:
ArrayList<String> ArrList = new ArrayList<String>(vector);
Below is the implementation of the above approach:
// Convert Vector to ArrayList in Java
import java.util.Vector;
import java.util.ArrayList;
public class GFG {
public static void main(String[] args)
{
// Create a Vector that contain strings
Vector<String> v = new Vector<String>();
// add values in vector
v.add("a");
v.add("b");
v.add("c");
v.add("d");
v.add("e");
// Display the Vector
System.out.println(" Vector : " + v);
// Convert Vector to ArrayList
ArrayList<String> Arrlist
= new ArrayList<String>(v);
// Display ArrayList
System.out.println("\n ArrayList : " + Arrlist);
}
}
Output
Vector : [a, b, c, d, e] ArrayList : [a, b, c, d, e]
Time Complexity: O(n)
Approach 3 : Using addAll()
- Declare and Initialize the Vector object with values.
- Now, declare the ArrayList.
- By using addAll() method, we can simply add all elements from Vector to ArrayList. Declare the vector object in the addAll() method i.e ArrayList_object.addAll(Vector_object).
- Print the ArrayList.
// Java Program to Convert Vector to ArrayList
import java.util.ArrayList;
import java.util.Vector;
public class GFG {
public static void main(String[] args)
{
// Create a Vector that contain strings
Vector<String> v = new Vector<String>();
// add values in vector
v.add("a");
v.add("b");
v.add("c");
v.add("d");
v.add("e");
// Display the Vector
System.out.println(" Vector : " + v);
// Converting vector to ArrayList
ArrayList<String> Arrlist = new ArrayList<String>();
Arrlist.addAll(v);
// Displaying the above ArrayList
System.out.println("\n ArrayList : " + Arrlist);
}
}
Output
Vector : [a, b, c, d, e] ArrayList : [a, b, c, d, e]