ArrayList.toArray() method in Java
Two reasons I can think of:
- Erasure means that the generic parameters aren't available at runtime, so an
ArrayList<String>
doesn't know that it contains strings, it's just the raw typeArrayList
. Thus all invocations oftoArray()
would have to return anObject[]
, which isn't strictly correct. You'd have to actually create a second array ofString[]
then iterate over the first, casting all of its parameters in turn to come out with the desired result type. - The way the method is defined means that you can pass in a reference to an existing array, and have this populated via the method. In some cases this is likely very convenient, rather than having a new array returned and then copying its values elsewhere.
In your code, the ArrayList
can contain anything, not only Strings. You could rewrite the code to:
ArrayList<String> listArray = new ArrayList<String>();
listArray.add("Germany");
listArray.add("Holland");
listArray.add("Sweden");
String []strArray = new String[3];
String[] a = listArray.toArray(strArray);
However, in Java arrays contain their content type (String) at runtime, while generics are erased by the compiler, so there is still no way for the runtime system to know that it should create a String[]
in your code.