In this article, we will write a Java program to convert Vector to ArrayList. In Java, both Vector and ArrayList implement the List interface and use dynamic arrays internally to store elements. However their performance for various operations such as search, insert, delete etc. differ in performance in different scenarios.
Note: You may also want to read: Vector to Array Conversion
Java Program to convert Vector to ArrayList
In this example, we have a Vector that contains String elements, we are converting it into an ArrayList by calling the constructor of ArrayList class while passing Vector as parameter.
import java.util.Vector;
import java.util.ArrayList;
public class VectorToArrayList {
public static void main(String[] args) {
// Creating a Vector of String type
Vector<String> vector = new Vector<String>();
// Adding elements to the vector
vector.add("Rahul");
vector.add("Steve");
vector.add("Jude");
vector.add("Locke");
vector.add("Mike");
vector.add("Robert");
//Displaying Vector elements
for (String str : vector){
System.out.println(str);
}
// Creating an ArrayList while passing Vector instance as a
// parameter to the constructor of ArrayList class
ArrayList<String> arraylist = new ArrayList<String>(vector);
// Displaying ArrayList Elements after conversion
System.out.println("\nArrayList Elements :");
for (String s : arraylist){
System.out.println(s);
}
}
}
Output:
Rahul
Steve
Jude
Locke
Mike
Robert
ArrayList Elements :
Rahul
Steve
Jude
Locke
Mike
Robert
Leave a Reply