Reputation: 139
I have below code
List<int[]> result = new ArrayList<int[]>();
result.add(new int[]{1,2});
result.add(new int[]{2,3});
int[][] re= result.toArray();
I tried to use toArray method to convert it to int[][]
data format. But, it will throw error,"incompatible types: Object[] cannot be converted to int[][]". Can someone explain the reason? and what I should do to convert it?
Upvotes: 2
Views: 105
Reputation: 40024
Try the following will work for any size list of arrays.
int[][] re= result1.toArray(int[][]::new);
System.out.println(Arrays.deepToString(re));
Prints
[[1, 2], [2, 3]]
Or three arrays
result1.add(new int[]{1,2,4});
result1.add(new int[]{2,3,5});
result1.add(new int[]{2,3,5});
int[][] re= result1.toArray(int[][]::new);
System.out.println(Arrays.deepToString(re));
Prints
[[1, 2, 4], [2, 3, 5], [2, 3, 5]]
Upvotes: 0
Reputation: 201409
Because List.toArray()
returns an Object[]
. You want List.toArray(T[])
(which returns a generic T[]
). Also, you can use <>
(the diamond operator) with your List
. Like,
List<int[]> result = new ArrayList<>();
result.add(new int[] { 1, 2 });
result.add(new int[] { 2, 3 });
int[][] re = result.toArray(new int[result.size()][]);
System.out.println(Arrays.deepToString(re));
Outputs
[[1, 2], [2, 3]]
Upvotes: 0