Search code examples
javavariablesloopsdynamiccreation

Is there a way I can 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 amount. So if I needed to create 10 arrays a loop would make 10(all named sequentially). But if I did not need 10 arrays the loop would create and many as needed.

I am envisioning something like this:

for(i=0 up to i=imax)

create arrayi

where i is the variable in the for loop.

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

thanks.


Solution

  • Yes; you can create an array of arrays. Let's say that you want arrays of 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
    

    However, you can not dynamically create variables called array0, array1, and so on. With multidimensional arrays, there is no need for such a collection of variables, because you can rather write arrays[0], arrays[1]; this is more flexible as well, since you can index into the array collection with arrays[i], which you couldn't do if you had array0, array1, and so on.