List to Array
There are two methods in List
to convert a List object to Array object as follows.
public Object[] toArray();
// Convert a List object to an Array object. All elements in this array will be type Object.
public <T> T[] toArray(T[] a);
// Convert a List<T> object to an Array object. All elements in this array will be type T.
First method
If we use the first method, a casting from Object
to T
is needed as below. It can be unsuccessful (down casting). Correspondingly, the code below will report Runtime Error.
List<String> list = new ArrayList<>();
String[] array = (String[]) list.toArray();
Second method
We cannot new a type T array with T arr=new T[size];
. So the second method returns what we want with following code. It use reflect
to create the array. a.getClass().getComponentType()
returns the type.
public <T> T[] toArray(T[] a) {
if (a.length < size)
a = (T[])java.lang.reflect.Array.
newInstance(a.getClass().getComponentType(), size);
System.arraycopy(elementData, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}
Inplementation
So the final implementation for the conversion from list to array is as below.
List<String> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
list.add(String.valueOf(i));
}
String[] array = new String[list.size()];
list.toArray(array);
Array to List
String[] array = {"1","2"};
List<String> list = Arrays.asList(array);