1

I created a list of int arrays, and I want to return it as a 2D array.

List<int[]> ans = new ArrayList<>();
int[][] toReturn = new int[ans.size()][];
return ans.toArray(toReturn);

How does this code work? What is the difference between list.toArray() and list.toArray(T[] a)?

2
  • 2
    Did you try the docs? Commented Dec 20, 2021 at 22:55
  • A List<List<Integer>> would work too, by the way Commented Dec 20, 2021 at 23:00

2 Answers 2

1

toArray creates a brand new array while toArray(T[] arr) tries to put all elements of the list into the provided arr array.

Sign up to request clarification or add additional context in comments.

1 Comment

And toArray() returns an Object array instead of T[].
1

you just need to use foreach loop for you list and a normal loop for the array.

public int[][] toArray(ArrayList<> inputList){
int[][] toReturn = new int[inputList.size()][];
int i =0;
for(int[] arrayOfInts : inputList){
  for(int j=0;j<arrayOfInts.length;j++){
  toReturn[i][j]=arrayOfInts [j] ;
  }
i++;
}
return toReturn  ;
}

Comments

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.