Learn to convert Vector to ArrayList in Java with example. We will also learn to convert arraylist to vector in Java.
1. Convert Vector to ArrayList
To convert a vector containing objects to an arraylist containing similar objects, we can use the arraylist constructor which accepts another collection and initialize the arraylist with the elements of vector.
import java.util.ArrayList; import java.util.Vector; public class ArrayListExample { public static void main(String[] args) { Vector<String> vector = new Vector<>(); vector.add("A"); vector.add("B"); vector.add("C"); vector.add("D"); ArrayList<String> arrayList = new ArrayList<>(vector); System.out.println(arrayList); } }
Program output.
[A, B, C, D]
2. Convert ArrayList to Vector
The conversion from arraylist to vector is very similar to previous example. Here we have to use the vector constructor. It accepts another collection and initialize the vector with the elements of arraylist.
import java.util.ArrayList; import java.util.Vector; public class ArrayListExample { public static void main(String[] args) { ArrayList<String> arrayList = new ArrayList<>(); arrayList.add("A"); arrayList.add("B"); arrayList.add("C"); arrayList.add("D"); Vector<String> vector = new Vector<>(arrayList); System.out.println(vector); } }
Program output.
[A, B, C, D]
Happy Learning !!
Read More:
A Guide to Java ArrayList
ArrayList Java Docs
Vector Java Docs
Are these examples backwards, or am I reading this wrong? Example 1 is for converting a vector into an arraylist, but the arraylist is made first, then the vector is created to copy the vector. Either way, it’s easy to figure out how it works, thanks to your examples.
Updated the examples.