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
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, a new array would have been created.
Second method is wrong.
fooList.toArray(); is Object
First method is typed. You creates new array with correct type and size (
new Foo[fooList.size()]), and then, you filled it using
Also you can use
fooList.toArray(new Foo) but this will give you an extra empty array object.
toArray works simple. If you call it without arguments, new Object is created.
If you give an array with correct type, it tryes to fill it, if it has enough space, or discard it, and create new array with given type.
If you are asking the difference between below methods;
First method will try to fit the elements in the list into the given
array instance, if it fails then creates a new array and proceed. Also the runtime type of the returned array is that of the specified array.
Second method creates a new array and proceed, and the return type is
Object causing class cast exception in your example.
Using asList() method
List<String> list = Arrays.asList(array);
Go to below link :