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[][]
Asked
Active
Viewed 801 times
1

Christophe Debove
- 6,088
- 20
- 73
- 124
3 Answers
7
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++;
}

Thomas Jungblut
- 20,854
- 6
- 68
- 91

ashutosh raina
- 9,228
- 12
- 44
- 80
-
any reason for the down vote ? if i am wrong at-least ,provide a reason , so that i can learn. – ashutosh raina Oct 23 '11 at 11:44
-
1Hi 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. – Thomas Jungblut Oct 23 '11 at 11:51
1
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.
-
-
Google guava has com.google.common.primitives.Ints which has a `toArray(Collection
)` method that's probably more efficient than `toPrimitive(foo.toArray())`. http://docs.guava-libraries.googlecode.com/git-history/v10.0.1/javadoc/com/google/common/primitives/Ints.html#toArray(java.util.Collection) – clstrfsck Oct 23 '11 at 11:40
0
I guess you will need two levels of loops to do that.

Maurice Perry
- 32,610
- 9
- 70
- 97
-
-
no: toArray cannot be used because invoking it on one of the inner lists will give an Integer[] which is different from an int[]. – Maurice Perry Oct 23 '11 at 11:20