The toArray() method in Java Collection converts a collection into an array.It returns an array containing all elements present in the collection.
- Used to convert collection elements into an array
- Supports different syntaxes for object and typed arrays
import java.io.*;
import java.util.ArrayList;
import java.util.List;
// Driver Class
class GFG {
// main function
public static void main(String[] args)
{
List<Integer> list1 = new ArrayList<Integer>();
list1.add(1);
list1.add(2);
list1.add(3);
list1.add(4);
Object[] array = list1.toArray();
System.out.print("The Array contains : ");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
}
Output
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.
Syntax
Object[] toArray();
Return Type: The return type of the above syntax is Object[] (Array).
Overloaded toArray() Method
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.
import java.io.*;
import java.util.ArrayList;
import java.util.List;
class GFG {
public static void main(String[] args)
{
List<String> list1 = new ArrayList<String>();
list1.add("Pen");
list1.add("Paper");
list1.add("Rubber");
list1.add("Pencil");
String[] array = list1.toArray(new String[0]);
System.out.println("The Array contains : ");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
}
Output
The Array contains : Pen Paper Rubber Pencil
Syntax
<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[].