Doris
Doris

Reputation: 139

How to convert a ArrayList of array of int to array of array of int in Java?

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

Answers (3)

WJS
WJS

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

Sergey Zh.
Sergey Zh.

Reputation: 437

int[][] re= result.toArray(new int[result.size()][]);

Upvotes: 1

Elliott Frisch
Elliott Frisch

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

Related Questions