在C/C++
我曾经做过
int arr[10] = {0};
...将我的所有数组元素初始化为 0。
Java中有类似的快捷方式吗?
我想避免使用循环,可以吗?
int arr[] = new int[10];
for(int i = 0; i < arr.length; i++) {
arr[i] = 0;
}
最佳答案
language spec 保证整数类型数组的默认值为 0。 :
Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10) [...] For type
int
, the default value is zero, that is,0
.
如果要将一维数组初始化为不同的值,可以使用java.util.Arrays.fill() (当然会在内部使用循环)。
关于java - 将所有数组元素初始化为零的任何快捷方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2154251/