Java ArrayList toArray() Method
The toArray()
method converts an ArrayList object into an array.
The syntax for the toArray()
method is:
arraylist.toArray(T[] arr)
Note: arraylist
is an object of the ArrayList class.
Parameter Description:
T[] arr
(optional parameter) - The array to store the elements.
Note: Here, T
refers to the type of the array.
Return Value
If the parameter T[] arr
is passed to the method, it returns an array of type T
.
If no parameter is passed, it returns an array of type Object
.
Example
Using an array parameter of specified type:
Example
import java.util.ArrayList;
import java.util.Comparator;
class Main {
public static void main(String[] args){
// Create a dynamic array
ArrayList<String> sites = new ArrayList<>();
sites.add("tutorialpro");
sites.add("Google");
sites.add("Wiki");
sites.add("Taobao");
System.out.println("Website List: " + sites);
// Create a new array of type String
// The array length is the same as the ArrayList length
String[] arr = new String[sites.size()];
// Convert ArrayList object to array
sites.toArray(arr);
// Print all elements of the array
System.out.print("Array: ");
for(String item:arr) {
System.out.print(item+", ");
}
}
}
Executing the above program outputs:
Website List: [tutorialpro, Google, Wiki, Taobao]
Array: tutorialpro, Google, Wiki, Taobao,
In the above example, we used the sort()
method on the array named sites
.
Notice this line:
sites.toArray(arr);
Here, we passed a String
type array as a parameter, and all elements are stored in the string array.
Note: The length of the array parameter passed should be equal to or greater than the arraylist. Here, we used the ArrayList size() method to create an array of the same size as the arraylist.
Using the toArray()
method without parameters:
Example
import java.util.ArrayList;
import java.util.Comparator;
class Main {
public static void main(String[] args){
// Create a dynamic array
ArrayList<String> sites = new ArrayList<>();
sites.add("tutorialpro");
sites.add("Google");
sites.add("Wiki");
sites.add("Taobao");
System.out.println("Website List: " + sites);
// Convert ArrayList object to array
// This method does not take parameters
Object[] obj = sites.toArray();
// Print all elements of the array
System.out.print("Array: ");
for(Object item : obj) {
System.out.print(item+", ");
}
}
}
Executing the above program outputs:
Website List: [tutorialpro, Google, Wiki, Taobao]
Array: tutorialpro, Google, Wiki, Taobao,
In the example above, we used toArray() to convert an ArrayList to an array.
Note: It is recommended to use the toArray() method with parameters.