Copy Elements of Vector to Java ArrayList
Since Vector class and ArrayList class both are part of Java Collections, ie Collection framework, so both of these classes can use methods available to the Collection framework. Copy() method is one of the methods of Collection Interface which is used to copy one list to another list, here list can be any collection like ArrayList, LinkedList, and Vector.
One important point to remember is that if the destination list length is greater than the length of the source list that is to copy, then the other element will remain unaffected, ie if the length of the destination list is 4 and the length of the source list is 3, then 3 elements of destination list would be replaced by elements of source list, but the 4th element, ie at index 3 would remain unaffected in the destination list.
Ways To copy elements of the Vector to ArrayList
- Passing in the constructor
- Adding one by one using add() method
Method 1: Passing in the constructor
- In this approach, we will simply pass the one Vector into the other List’s constructor.
- By using this approach if we change in first vector values then it will not change the values of the List.
- This is the easiest way to copy elements of the vector to Java ArrayList.
-----Iterating over the List---- 11 22 24 39
Method 2: Adding one by one using add() method
- In this approach, we will iterate over each element of Vector and add that element to the List.
- Here if you change the Vector element then it will not change the elements of the List.
- It is not the best approach, but it’s a simple iteration process.
-----Iterating over the List---- 50 24 95 31