Java - Bulk Initialize an Array with Arrays.fill()
Introduces the Arrays.fill() method, which is used to initialize an array in bulk.
Bulk Array Initialization - Arrays.fill()
In Java, there are cases where you need to put the same value into an array in bulk when initializing it.
Usually, you might think of a method like the following, but this method looks too inefficient.
package com.devkuma.basic.array;
import java.util.Arrays;
public class ArrayFill1 {
public static void main(String args[]) {
int[] arr = new int[5];
for (int i = 0; i < arr.length; i++) {
arr[i] = 10;
}
System.out.println(Arrays.toString(arr));
}
}
Execution result:
[10, 10, 10, 10, 10]
Java provides the Arrays.fill() method for this situation.
If you apply the Arrays.fill() method to the code above, it can be changed as follows.
package com.devkuma.basic.array;
import java.util.Arrays;
public class ArrayFill1 {
public static void main(String args[]) {
int[] arr = new int[5];
Arrays.fill(arr, 10);
System.out.println(Arrays.toString(arr));
}
}
Execution result:
[10, 10, 10, 10, 10]