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

3 Answers 3

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++;
}
Sign up to request clarification or add additional context in comments.

2 Comments

any reason for the down vote ? if i am wrong at-least ,provide a reason , so that i can learn.
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.
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.

2 Comments

Added Apache Commons ArrayUtils class for completeness
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/…
0

I guess you will need two levels of loops to do that.

2 Comments

there is not default util method?
no: toArray cannot be used because invoking it on one of the inner lists will give an Integer[] which is different from an int[].

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.