Convert list to array using toArray

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();


ANSWERS:


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.


Second method is wrong.

type of 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 fooList.toArray()

Also you can use fooList.toArray(new Foo[0]) 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;

list.toArray(array);
list.toArray();

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 :



 MORE:


 ? Dynamically allocating array in a function in c++
 ? Two-dimensional dynamic allocated arrays created inside a class in C++
 ? Regarding dynamic memory allocation in C++
 ? Regarding dynamic memory allocation in C++
 ? Regarding dynamic memory allocation in C++
 ? Any way to prevent dynamic allocation of a class?
 ? Passing character pointers into a function and dynamically allocating memory
 ? when populating an std::vector by value, will dynamically allocated object pointers be deleted?
 ? pointer and dynamic memory allocation
 ? C dynamic allocated pointer to main function