English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The Java ArrayList toArray() method converts an ArrayList to an array and returns it.
The syntax of toArray() method
arraylist.toArray(T[] arr)
T [] arr(Optional)- Array used to store ArrayList elements
Note:Here, T specifies the type of the array.
If the method is passed an array T[]arr, it returns an array of type T
If no parameters are passed, it returns an array of type Object
import java.util.ArrayList; class Main { public static void main(String[] args) { ArrayList<String> languages = new ArrayList<>(); //Add elements to the ArrayList languages.add("Java"); languages.add("Python"); languages.add("C"); System.out.println("ArrayList: ")} + languages); //Create a new String type array //The size of the array is the same as the ArrayList String[] arr = new String[languages.size()]; //Convert ArrayList to Array languages.toArray(arr); //Print all elements of the array System.out.print("Array: "); for(String item:arr) { System.out.print(item+", "); } } }
Output Result
ArrayList: [Java, Python, C] Array: Java, Python, C,
In the above example, we created an ArrayList named languages. Note this line,
languages.toArray(arr);
Here, we pass a String type array as a parameter. Therefore, all elements of the ArrayList are stored in the array.
Note:The size of the array passed as a parameter should be equal to or greater than the ArrayList. Therefore, we useArrayList size()method is used to create an array of the same size as the ArrayList.
import java.util.ArrayList; class Main { public static void main(String[] args) { ArrayList<String> languages = new ArrayList<>(); //Add elements to the ArrayList languages.add("Java"); languages.add("Python"); languages.add("C"); System.out.println("ArrayList: ")} + languages); //Convert ArrayList to Array //The method has no parameters Object[] obj = languages.toArray(); //Print all elements of the array System.out.print("Array: "); for(Object item : obj) { System.out.print(item+", "); } } }
Output Result
ArrayList: [Java, Python, C] Array: Java, Python, C,
In the above example, we used the toArray() method to convert an ArrayList to an array. Here, this method does not include optional parameters. Therefore, it will return an object array.
Note: It is recommended to use the toArray() method with parameters.