简体   繁体   中英

How can I convert a List<int[]> to a 2D array?

I have a List of arrays declared like this :

List<int[]> ls = new ArrayList<int[]>();

Here I am trying to keep a list with arrays like this : [ [1,2,3] ,[2,3],[4,5] ]

To add an array to this list I do this in a for loop:

int[] a = new int[2];
a[0] = arr[i];
a[1] = arr[i]+k;
ls.add(a);

I want to convert this list of arrays in a matrix that has 1 rows and list.size as colums like this :

[[0, -1], [-1, -2], [2, 1], [1, 0]]

How can I do this?

Thanks!

Simple, invoke toArray :

// new double-dimension int array
//                   | conversion here
//                   |                  | specifying 1st dimension's size as list's 
//                   |                  | size
int[][] converted = ls.toArray(new int[ls.size()][]);

// test it
System.out.println(Arrays.deepToString(converted));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM