Java toArray() Method: Convert Collections to Arrays
In Java, toArray() is a commonly used method that is used to convert a collection into an array. It can be used on various collection types such as List, Set, and others.
Grammar:
<T> T[] toArray(T[] a)
Parameters:
- a: Specifies the type of array to convert to. If the specified array size is smaller than the collection size, a new array of the same type will be created. If the specified array size is larger than the collection size, the collection elements will be filled into the specified array, with the last element set to null.
Return value:
- Return an array containing the elements of the collection.
Can you please repeat that in English for me?
List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Orange");
String[] array = list.toArray(new String[list.size()]);
System.out.println(Arrays.toString(array)); // Output: [Apple, Banana, Orange]
In the above example, we converted a List containing three elements into an array of String type. We first created an array with the same size as the collection, then copied the elements of the collection into this array. Finally, we printed the output result using the Arrays.toString() method.
It is important to note that when using the toArray() method, if no parameter is provided, it will return an array of type Object[]. Therefore, if we want to convert a collection to a specific type of array, we must explicitly specify the array type as a parameter.