![]() |
VOOZH | about |
The toArray() method in Java Collection converts a collection into an array.It returns an array containing all elements present in the collection.
The Array contains : 1 2 3 4
Explanation: The example given above returns an array of type Object containing elements as of list1. We use this syntax when we don't want a particular return type.
Object[] toArray();
Return Type: The return type of the above syntax is Object[] (Array).
This overloaded method of toArray() returns an array containing all elements inside the collection where the type of the returned array is what we specify inside the argument of the toArray() method.
The Array contains : Pen Paper Rubber Pencil
<T> T[] toArray(T[] arr);
Parameter: T denotes the type of element stored in the collection
Return Type: The return type is what we specify inside the argument(i.e. T).
Note: The overloaded toArray() provides compile-time type safety by returning a specific type array (e.g., Integer[], String[]), while the default version returns an Object[].