gpt4 book ai didi

java - 将所有数组元素初始化为零的任何快捷方式?

转载 作者:bug小助手 更新时间:2023-10-28 10:39:46 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com