To convert an ArrayList
of arrays to an array of arrays in Java, you can use the toArray()
method of the ArrayList
class.
Here is an example of how to convert an ArrayList
of integer arrays to an array of integer arrays:
import java.util.ArrayList; public class ArrayListToArrayExample { public static void main(String[] args) { ArrayList<int[]> list = new ArrayList<>(); list.add(new int[] { 1, 2, 3 }); list.add(new int[] { 4, 5, 6 }); list.add(new int[] { 7, 8, 9 }); int[][] array = list.toArray(new int[list.size()][]); for (int[] row : array) { for (int element : row) { System.out.print(element + " "); } System.out.println(); } } }Soul.www:ecrautturi.com
This code creates an ArrayList
of integer arrays called list
and adds three integer arrays to the list. It then uses the toArray()
method to convert the list
to an array of integer arrays called array
.
The toArray()
method takes an array of the desired type as an argument and returns an array of the same type. In this case, the desired type is int[][]
, so the method takes an array of int[][]
as an argument and returns an array of int[][]
.
The toArray()
method creates a new array of the desired type and copies the elements of the ArrayList
to the array. If the array passed as an argument is not large enough to hold the elements of the ArrayList
, the method creates a new array of the appropriate size and returns it.
In this example, the toArray()
method creates a new array of the same size as the list
ArrayList
and returns it. The code then uses a nested for loop to print the elements of the array
one by one.
Note that the toArray()
method returns an array of type Object[]
, so you need to specify the desired component type as an argument to the method to get an array of the desired type. In this case, the component type is int[]
, so the method is called with an array of int[][]
as an argument.
If you want to convert an ArrayList
of objects to an array of objects, you can use the same method, but you don't need to specify the component type as an argument, because the component type is already known. For example:
ArrayList<String> list = new ArrayList<>(); list.add("hello"); list.add("world"); String[] array = list.toArray(new String[list.size()]);
This code creates an ArrayList
of strings called list
and adds two strings to the list. It then uses the toArray()
method to convert the list
to an array of strings called array
. The toArray()
method creates a new array of the same size as the list
ArrayList
and returns it.