Hello, how in Java can I convert a list of numeric arrays into an array of arrays (ArrayList int [] to int [] [])?
1 answer
The ArrayList class has a toArray method that allows you to create an array based on list items.
Below is a demo program.
/* package whatever; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ class Ideone { static int [] make_array( int n ) { int [] a = new int[n]; for ( int i = 0; i < a.length; i++ ) a[i] = i; return a; } public static void main (String[] args) throws java.lang.Exception { ArrayList<int []> lst = new ArrayList<int[]>(); for ( int i = 0; i < 10; i++ ) { lst.add( make_array( i + 1 ) ); } int[][] a = new int[lst.size()][]; lst.toArray( a ); for ( int[] row : a ) { for ( int x : row ) System.out.print( x + " " ); System.out.println(); } } } Console output
0 0 1 0 1 2 0 1 2 3 0 1 2 3 4 0 1 2 3 4 5 0 1 2 3 4 5 6 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 8 0 1 2 3 4 5 6 7 8 9 - Thank you, will this code be correct in my case?
ArrayList<int[]> x = new ArrayList<>(); int[][] y = x.toArray(new int[x.size()][]);- Flappy - @Flappy I added an example to my answer. :) - Vlad from Moscow
|