There are several ways to convert ArrayList to Vector. We can use a vector constructor for converting ArrayList to vector. We can read ArrayList elements one by one and add them in vector.
Approach 1: (Using Vector Constructor)
- Create an ArrayList.
- Add elements in ArrayList.
- Create a vector and pass the ArrayList in Vector Constructor.
Vector(Collection c): Creates a vector that contains the elements of collection c.
Vector<E> v = new Vector<E>(Collection c);
Example:
Java
import java.util.ArrayList;
import java.util.Vector;
public class GFG {
public static void main(String[] args)
{
ArrayList<Integer> ArrList = new ArrayList<Integer>();
ArrList.add( 10 );
ArrList.add( 20 );
ArrList.add( 30 );
ArrList.add( 40 );
ArrList.add( 50 );
System.out.println( " ArrayList : " + ArrList);
Vector<Integer> vector = new Vector<Integer>(ArrList);
System.out.println( " Vector : " + vector);
}
}
|
Output ArrayList : [10, 20, 30, 40, 50]
Vector : [10, 20, 30, 40, 50]
Approach 2: (Using for loop)
- Create a ArrayList.
- Add some values in ArrayList.
- Create an Vector.
- Execute a loop.
- Traverse each element of ArrayList from the left side to the right side.
- Add the ArrayList elements in Vector.
Example:
Java
import java.util.Vector;
import java.util.ArrayList;
public class GFG {
public static void main(String[] args)
{
ArrayList<String> Arrlist = new ArrayList<String>();
Arrlist.add( "A" );
Arrlist.add( "B" );
Arrlist.add( "C" );
Arrlist.add( "D" );
Arrlist.add( "E" );
System.out.println( " ArrayList : " + Arrlist);
Vector<String> v = new Vector<String>();
int n = Arrlist.size();
for ( int i = 0 ; i < n; i++) {
v.add(Arrlist.get(i));
}
System.out.println( "\n vector : " + v);
}
}
|
Output ArrayList : [A, B, C, D, E]
vector : [A, B, C, D, E]
Approach 3: (Using addAll() method)
This method is used to append all the elements from the collection passed as a parameter to this function to the end of a vector keeping in mind the order of return by the collection’s iterator.
Syntax:
boolean addAll(Collection C)
Parameters: The method accepts a mandatory parameter C which is a collection of ArrayList. It is the collection whose elements are needed to be appended at the end of the vector.
Return Value: The method returns True if at least one action of append is performed, else False.
Example:
Java
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
ArrayList<String> listStrings = new ArrayList<>();
listStrings.add( "Geeks" );
listStrings.add( "for" );
listStrings.add( "Geeks" );
Vector<String> vStrings = new Vector<>();
vStrings.addAll(listStrings);
System.out.println( "Vector contains: " + vStrings);
}
}
|
OutputVector contains: [Geeks, for, Geeks]