Any shortcut to initialize all array elements to zero?
To initialize all elements of an array to zero in Java, you can use the Arrays.fill
method from the java.util
package.
For example, to initialize an array of integers to zero:
int[] array = new int[10];
Arrays.fill(array, 0);
This will fill the entire array with the value 0
.
You can also use the Arrays.fill
method to initialize a part of the array to a specific value.
For example:
int[] array = new int[10];
Arrays.fill(array, 3, 5, 0);
This will fill the elements of the array with index 3 to index 4 (inclusive) with the value 0
.
Keep in mind that the Arrays.fill
method modifies the original array and does not create a new array. If you want to create a new array with all elements initialized to zero, you can use the new
operator along with the Arrays.fill
method.
For example:
int[] array = new int[10];
array = Arrays.stream(array).map(x -> 0).toArray();
This will create a new array with all elements set to zero, using the Java Stream API.
You can also use a loop to initialize all elements of the array to zero.
For example:
int[] array = new int[10];
for (int i = 0; i < array.length; i++) {
array[i] = 0;
}
This will iterate over all elements of the array and set them to zero.