How to initialize all the elements of an array with 0 (Something like memset in C)
ʻArrays.fill (array, initialization value)`
import java.util.Arrays;
public class HelloWorld {
public static void main (String[] args) {
int[] intArray = new int[10];
Arrays.fill(intArray, 0); //Specify the initialization value with the second argument
System.out.println(Arrays.toString(intArray));
}
}
// => [0, 0, 0, ...]
This method can also handle strings
import java.util.Arrays;
public class HelloWorld {
public static void main (String[] args) {
String[] str = new String[5];
Arrays.fill(str, "_"); //Specify the initialization value with the second argument
System.out.println(Arrays.toString(str));
}
}
// => ["_", "_", "_", ...]
Recommended Posts