Try the approach below:
public void fill2D(int[][] matrix, int value) {
int m = matrix.length;
int n = matrix[0].length;
for (int i = 0; i < m * n; i++) {
int row = i / n;
int col = i % n;
matrix[row][col] = value;
}
}
Usage:
@Test
public void test() {
int[][] matrix = new int[5][6];
fill2D(matrix, -1);
for (int[] row : matrix) {
System.out.println(Arrays.toString(row));
}
}
Benchmark test
private final int M = 500;
private final int N = 500;
@Benchmark
public void method1() {
int[][] matrix = new int[M][N];
for (int i = 0; i < M * N; i++) {
int row = i / N;
int col = i % N;
matrix[row][col] = -1;
}
}
@Benchmark
public void method2() {
int[][] matrix = new int[M][N];
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
matrix[i][j] = -1;
}
}
}
@Benchmark
public void method3() {
int[][] matrix = new int[M][N];
for (int[] row : matrix) {
Arrays.fill(row, -1);
}
}
Result
Benchmark Mode Cnt Score Error Units
BenchMarkTest.method1 avgt 20 0,600 ± 0,002 ms/op
BenchMarkTest.method2 avgt 20 0,191 ± 0,003 ms/op
BenchMarkTest.method3 avgt 20 0,216 ± 0,021 ms/op
fillin classArrays? It contains aforloop, so in essence you are executing a loop even when you are initializing a one-dimensional array with that method.new int[row][col]rather than doubly initialise the arrays.Arrays.xxx()do not return the array as you could then have usedmatrix = setAll(new int[row][], i -> fill(new int[col], -1));