SeizedSilver SeizedSilver - 1 year ago 126
Java Question

Assigning array from ArrayList to an int array with ArrayList.get(). Java

I have an ArrayList of int arrays.
I know the index of the item I want in the ArrayList.
i want to initialize a new int[] to the same value as that array stored ArrayList.
simplified example:

ArrayList arrList = new ArrayList();
int[] arrOne = {1, 2, 3, 4};
int[] arrTwo = {5, 6, 7, 8};
int[] containerOne = arrList.get(0);
int[] containerTwo = arrList.get(1);

I get:
incompatible types: object cannot be converted to int[]

Why won't this work? Hopefully this is formatted correctly.

Answer Source

Why won't this work?

Because you are using raw types. ArrayList without a type parameter means "a list of objects whose type I can't tell you". If you get an element from this list, its type is not known to the compiler.

If you declare arrList as an ArrayList<int[]> ... your code should work.

    ArrayList<int[]> arrList = new ArrayList<>();

Alternatively, type-cast the result of the get calls; e.g.

    int[] containerOne = (int[]) arrList.get(0);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download