2

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?

3
  • Why not just start with new int[][]? Commented Aug 10, 2021 at 22:16
  • 1
    @OneCricketeer I am doing some leetcode questions, so for this one, at first I don't know the size of the array. So I created a arraylist to add value dynamically. But the return needs int[][] Commented Aug 10, 2021 at 22:19
  • Most questions arent picky about data structures, only the final output... In which case, List<List<Integer>> would suit you better Commented Aug 10, 2021 at 22:24

3 Answers 3

1
int[][] re= result.toArray(new int[result.size()][]);
2
  • That's a single dimension array. Commented Aug 10, 2021 at 22:24
  • I think I understand what you mean, thank you! Inspired by your comment, I checked the document again. I found out there is another api "docs.oracle.com/javase/8/docs/api/java/util/…"... so, I tried this int[][] re= result.toArray(new int[result.size()][]); and it works! Commented Aug 10, 2021 at 22:27
0

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]]
0

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]]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.