When I try to make a two-dimensional array normally in Java, the number of elements of the second element is all constant, but since I found out how to change the number of elements of the second element depending on the first element and other variables. I'll share it!
int[][] arrays = new int[m][n];
//Prepare an array containing the number of elements of the second element (anything is fine)
int[] array = {2, 3, 5};
//Define the number of elements only for the first element
int[][] arrays = new int[array.length][];
for (int i = 0; i < arrays.length; i++){
//Define the number of elements of the second element while turning the first element with a for statement etc.
arrays[i] = new int[array[i]];
}
//bonus
System.out.println(arrays.length);
for (int i = 0; i < arrays.length; i++){
System.out.println(arrays[i].length);
}
//output
//3
//2
//3
//5
In the same way
int arrays[][][] =new array [m][n];
//abridgement
arrays[i][j] = new int[array[j]];
You should be able to do it in any dimension! (unconfirmed)
I think that the array will be more convenient by dynamically changing the number of elements in this way! !! If you have any mistakes, feel free to comment! !!
Recommended Posts