![]() |
VOOZH | about |
In Java, the toArray() method is the part of the AbstractCollection class. It is used to convert collections like List, Set, etc. into an array. It copies all the elements from the collection into a new array.
Example:
The AbstractCollection: [C, JS, C++, Java] The array is: C JS C++ Java
Now, there are two versions of toArray() method i.e. one without parameter and one with the parameter.
Copies all the elements from the collection into a new array.
Syntax:
Object[] arr = AbstractCollection.toArray();
Example: This example demonstrates converting a PriorityQueue to an array using the toArray() and printing the array elements.
The AbstractCollection: [5, 10, 25, 20, 15, 30] The array is: 5 10 25 20 15 30
In Java, toArray(arr[]) method is used to covert an AbstractCollection into an array of specified type. It fills the provided array with the elements of the collection. If the provided array is large enough it is used directly otherwise, a new array of the appropriate type and size is created.
Syntax:
Object[] toArray(T[] arr)
Exception:
The toArray(arr[]) method may throws two exceptions:
Example 1: This example demonstrates how to convert an AbstractCollection to an array using toArray(arr[]) method when the provided array is of the same size as the collections.
The AbstractCollection: [For, Geeks, Geeks] The Array is: For Geeks Geeks
Example 2: This example demonstrates how the toArray(arr[]) method in java automatically resizes the array when it is smaller than the AbstractCollection size.
The AbstractCollection: [For, Geeks, Geeks, Java] The Array is: For Geeks Geeks Java
Example 3: This example demonstrates how the toArrray(arr[]) method in java copies element from an AbstractCollection to an array, even when the array is larger than the collection.
The AbstractCollection: [For, Geeks, Geeks, Java] The Array is: For Geeks Geeks Java null null
Example 4: This example demonstrates that passing a null array to the toArray() method in Java throw a NullPointerException.
The AbstractCollection: [For, Geeks, Geeks] Exception: java.lang.NullPointerException