I have an old function I can't change who want an int[][] for parameter is there a way to map
ArrayList<ArrayList<Integer>> to int[][]
3 Answers
Get the size of the ArrayLists into i and j ,respectively Increment i and j according to your logic
int i = 0;
for(ArrayList<Integer> a1 : outer){
int j=0;
for(Integer k : a1){
yourarray[i][j++] = k;
}
i++;
}
2 Comments
ashutosh raina
any reason for the down vote ? if i am wrong at-least ,provide a reason , so that i can learn.
Thomas Jungblut
Hi sorry, you are never resetting "j". This will yield to fancy Index Out of Bounds exceptions. And in Java you should write variable names lowercase.
I agree with Maurice.
To convert List<Integer> to int[], there's a nice answer here that you may find usefull.
Also note that Apache Commons has a ArrayUtils class, which has a method toPrimitive() that does exactly this for one array level.
Edit (see comments below):
msandiford also mentions the existence of guava Ints class that provides a static int[] toArray(Collection<Integer> collection) method.
2 Comments
Laurent'
Added Apache Commons ArrayUtils class for completeness
clstrfsck
Google guava has com.google.common.primitives.Ints which has a
toArray(Collection<Integer>) method that's probably more efficient than toPrimitive(foo.toArray()). docs.guava-libraries.googlecode.com/git-history/v10.0.1/javadoc/…I guess you will need two levels of loops to do that.
2 Comments
Christophe Debove
there is not default util method?
Maurice Perry
no: toArray cannot be used because invoking it on one of the inner lists will give an Integer[] which is different from an int[].