1

Anyone know how to add an int[] array into a 2d ArrayList<ArrayList<Integer>>?

The code...

import java.util.ArrayList;
import java.util.Arrays;

public class Test2 {
    public static void main(String[] args) {
        int[] intArray = {1,1,1,1};
        ArrayList<ArrayList<Integer>> list = new ArrayList<>();

        list.add(new ArrayList<Integer>(Arrays.asList(intArray))); // <- compile error
    }
}
0

2 Answers 2

7

change your int array to an Integer array.

Integer [] intArray = {1,1,1,1};
Sign up to request clarification or add additional context in comments.

8 Comments

The problem here is in my application, the arrays indexes get passed through multiple methods as an int for mutable changes and acquiring results. I was hoping to convert it just before it gets added to the 2d ArrayList. Is it possible to convert while adding it?
There is autoboxing from int to Integer but no autoboxing from int[] to Integer[]
you could leave it as type int and try this list.add(Arrays.stream(intArray).boxed().collect(Collectors.toCollection(ArrayList::new)));
I see, so even though it worked with String[] array = {"one","one","one","one"}; and ArrayList<ArrayList<String>> list = ArrayList<>(); and then list.add(new ArrayList<String>(Arrays.asList(tempResult)))... it only worked with this because String was the same type, and int and Integer are different and "can't be autoboxed from int[] to Integer[]"?
Yep, that is the jist
|
1

Make your ArrayList an ArrayList of int[]:

ArrayList<int[]> list = new ArrayList<>();
list.add(intArray); // should work now

Comments

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.