Search code examples
javaarraysdynamicintegerfill

How to fill an array if its size is apriori unknown


How to avoid java.lang.ArrayIndexOutOfBoundsException if the size of indexes is apriori unknown?

Integer[] indexes = new Integer[]{};
int num = 0;
for (ArrayList<Integer[]> arr: list) {
   for (int i=0; i<arr.length; i++) {
       indexes[num] = arr[i];
       num++;
   }
}

The goal is to get a one-dimensional array Integer[] indexes from a two-dimensional array ArrayList<Integer[]> list.

UPDATE:

For instance:

list[0] = {1,2,3}
list[1] = {4}

I need to get:

indexes = {1,2,3,4}

Solution

  • Use a new ArrayList (newList.add(arr[i])) and then call toArray():

    Integer[] indexes = newList.toArray(new Integer[newList.size()]);
    

    A less effective solution that doesn't use an intermediate list - you can loop the whole structure once just to count the elements. Then instantiate the array with the precalculated size.