source: https://blogs.oracle.com/sankarblog/entry/code_example_list_toarray_t
I need to convert a List into an array and I saw java.util.List's " T[] toArray(T[] a)" fitting my bill. This syntax didn't really looked natural to me and I wrote this test case.
import java.util.ArrayList;
public class ToArray {
public static void main(String args[]) {
ArrayList list = new ArrayList();
list.add(1);
list.add(2);
list.add(3);
Integer[] ints = list.toArray(new Integer[]{});
for (Integer i : ints) {
System.out.println(i);
}
}
}
Output of theabove code snippet is:
$ java ToArray
1
2
3
I was bit confused whether the parameter to the toArray should be the same array
Integer[] ints = {};
ints = list.toArray(ints);
or any array of the same type
Integer[] ints = list.toArray(new Integer[]{});
Both of the above two works and what matters is only is the only type.