1

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

Christophe Debove
  • 6,088
  • 20
  • 73
  • 124

3 Answers3

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

Community
  • 1
  • 1
Laurent'
  • 2,611
  • 1
  • 14
  • 22
  • Added Apache Commons ArrayUtils class for completeness – Laurent' Oct 23 '11 at 11:19
  • 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