Is there any way to create a variable number of arrays using loops in Java?
I wonder if there is a way to create arrays in Java based on variable numbers Therefore, if I need to create 10 arrays, the loop will generate 10 (all named sequentially) But if I don't need 10 arrays, the loop can create multiple arrays as needed
I imagine 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 will generate: array0, array1, array2, array3
thank you.
Solution
Yes; You can create an array Suppose you want an int array:
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 cannot dynamically create variables named array0, array1, etc For multi-dimensional arrays, such a variable set is not required, because you can write array [0], array [1]; This is also more flexible because you can use arrays [i] to index the array collection. If you have array0, array1, etc., you cannot do this