With easy-to-follow examples, learn to convert a Vector into an ArrayList and vice-versa in Java.
1. Converting 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 the vector.
Vector<String> vector = new Vector<>();
vector.add("A");
vector.add("B");
vector.add("C");
vector.add("D");
ArrayList<String> arrayList = new ArrayList<>(vector); //[A, B, C, D]
2. Converting ArrayList to Vector
The conversion from ArrayList to vector is very similar to the previous example. Here we have to use the Vector constructor. It accepts another collection and initializes the vector with the elements of ArrayList.
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("A");
arrayList.add("B");
arrayList.add("C");
arrayList.add("D");
Vector<String> vector = new Vector<>(arrayList);
Happy Learning !!
Leave a Reply