Java Collection toArray() Method (original) (raw)
Last Updated : 29 Dec, 2023
The **toArray() method of Java Collection returns an array containing elements that are inside the calling collection. This article will discuss the **toArray() method, its syntaxes, how it works, and some code examples.
Syntax of toArray() Method
Object[] toArray();
**Return Type: The return type of the above syntax is Object[] (Array).
Examples of Java toArray() Method
The example given below returns an array of type **Object containing elements as of list1. We use this syntax when we don't want a particular return type.
Below is the implementation of the above method:
Java `
// Java Program to Java toArray() Method import java.io.*; import java.util.ArrayList; import java.util.List;
// Driver Class class GFG { // main function public static void main(String[] args) { List list1 = new ArrayList();
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
O**verloaded 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.
Syntax of Method
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).
Example of Overloaded toArray() Method
In the example below, we have made some changes we need to understand before going further.
String[] array=list1.toArray(new String[0]);
This line is different from the above example. Here in this line, we have passed a string array as an argument to the function. Due to this, it returns us an array of string** type (i.e. name array in this example ) having the same size and containing all the elements as of calling collection **list1.
**Note: The major advantage of using the overloaded Overloaded toArray() method is it provides compile-time type safety as it returns an array of specific type only(e.g. Integer,String etc.) but the first syntax returns an array of Object type.
Example of O**verloaded toArray() Method
Below is the implementation of the above method:
Java `
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