Please the read the question instead of assuming this is a duplicate.
In the codebase I am working on I have a list of Foo objects:
private List<Foo> fooList;
Could someone please explain to me the difference(s) between this line of code:
Foo foos[] = fooList.toArray(new Foo[fooList.size()]);
and this line?
Foo foos[] = (Foo[]) fooList.toArray();
The difference is, 2nd one would throw a ClassCastException
at runtime. The parameterless List#toArray()
method creates an Object[]
internally, which you cannot cast to Foo[]
. Since generic type information is erased by compiler, the type of the list is not known at runtime. So, you cannot know the actual type to create an array (i.e, you cannot create an array like - new T[size]
). That is why it creates an Object[]
.
To overcome this issue, a generic method List#toArray(T[])
is there, in which you can pass the actual array, that will be filled by the elements of the ArrayList
. If the size of the array is not enough to fit the elements, a new array is internally created. So, since you pass new Foo[fooList.size()]
, it will get filled by the elements of the list. However, had you passed a new Foo[0]
, a new array would have been created.