Home > Back-end >  How to use the list.toArray() method in Java for a two-dimensional array
How to use the list.toArray() method in Java for a two-dimensional array

Time:12-21

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)?

CodePudding user response:

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

CodePudding user response:

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  ;
}
  • Related