Code Example: List.toArray(T[] a)
Tuesday Mar 06, 2007
Most of the time, I write small code snippets and wrap them in a small test case to test my assumptions before I put them in a real places. For long a time, I wanted to capture these code snippets some where with my observations. Suddenly I realized, I could blog them too. I hope to continue this practice, but I am not very positive though 
Coming to my code snippet, I need to convert a List into an array and I saw java.util.List's "
import java.util.ArrayList;
public class ToArray {
public static void main(String args[]) {
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.










