Is there a way to create a variable number of arrays using a loop in java?

I am wondering if there is a way to create arrays in java based on a variable sum. Therefore, if I need to create 10 arrays, the loop will be 10 (they are all called sequentially). But if I didn’t need 10 arrays, the loop would create a lot as needed.

I imagine something like this:

for(i=0 up to i=imax)

create arrayi

where i am the variable in the for loop.

If imax is set to 3, it will produce: array0, array1, array2, array3

thank.

+3
source share
3 answers

Yes; you can create an array of arrays. Say you want arrays int:

int numberOfArrays = 10;
int[][] arrays = new int[numberOfArrays][];
for (int i = 0; i < numberOfArrays; i++)
    arrays[i] = new int[x]; // Where x is the size you want array i to be

array0, array1 .. , arrays[0], arrays[1]; , arrays[i], , array0, array1 ..

+7

, ...

0

Java does not allow such metaprogramming. You cannot programmatically declare variables.

As @Aasmund writes, you can declare an array to hold your arrays.

For your specific question, this is the result:

String[][] array = new String[IMAX][];
for (int i = 0; i < array.length; ++i) {
  array[i] = createArray(...);
}

// cannot use 'array2', but something close:
String[] contents = array[2];
0
source

All Articles