A collection stores a group of objects dynamically, while an array stores elements in a fixed-size structure. Java provides the toArray() method to convert a collection, such as a List, into an array.
- The toArray() method can convert a List into an array.
- Java provides both toArray() and toArray(T[] a) for converting collections to arrays.
Methods To Convert Collection To Array
The following are the commonly used methods to convert a collection into an array in Java.
1. Using toArray() Method
The toArray() method of the Collection interface returns an array containing all elements of the collection in their proper order.
Syntax:
Object[] toArray();
import java.util.*;
public class GFG {
public static void main(String[] args)
{
List<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
list.add("C++");
list.add("JavaScript");
// Converting the list into an Object array
Object[] arr = list.toArray();
// Printing the array elements
System.out.println("Array elements:");
for (Object element : arr) {
System.out.println(element);
}
}
}
Output
Array elements: Java Python C++ JavaScript
Explanation: The toArray() method converts the List into an Object[] array. The returned array contains the elements in the same order as they appear in the list.
2. Using toArray(T[] a) Method
The overloaded toArray(T[] a) method allows us to specify the type of array that should be returned. This is useful when we want an array of a specific type instead of an Object[].
Syntax:
<T> T[] toArray(T[] a);
import java.util.*;
public class GFG {
public static void main(String[] args)
{
List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Mango");
list.add("Orange");
list.add("Grapes");
// Converting the list into a String array
String[] arr = list.toArray(new String[0]);
// Printing the array
System.out.println("Array: " + Arrays.toString(arr));
}
}
Output
Array: [Apple, Mango, Orange, Grapes]
Explanation: Here, toArray(new String[0]) converts the List<String> into a String[]. The resulting array contains all the elements of the list in the same order.
Note: The toArray(T[] a) form is commonly used when working with generic collections because it allows the resulting array to have a specific type, such as String[], Integer[], etc.