如何在Java中将数组的所有元素初始化为任何特定值 [英] How to initialize all the elements of an array to any specific value in java
问题描述
在C/C++
中,我们具有memset()
函数,可以满足我的愿望,但是在Java
中,我如何将所有元素初始化为特定值?每当我们写int[] array=new int[10];
时,这都会简单地初始化一个大小为10的数组,其中所有元素都为零.我只想为我的一个数组更改此初始化整数.即我要初始化一个数组,该数组的所有元素均等于-1
.否则,我必须在初始化后立即放置一个for
循环,其范围从索引0
到索引size-1
,并且在该循环内部,我正在将元素分配给-1
.下面是用于更多理解的代码-
In C/C++
we have memset()
function which can fulfill my wish but in Java
how can i initialize all the elements to a specific value? Whenever we write int[] array=new int[10];
, this simply initialize an array of size 10 having all elements equal to zero. I just want to change this initialization integer for one of my array. i.e. I want to initialize an array which has all elements equal to -1
. Otherwise I have to put a for
loop just after initialization, which ranges from index 0
to index size-1
and inside that loop, I am assigning element to -1
. Below is the code for more understanding-
int[] array = new int[10];
for (int i = 0; i < size; i++) {
array[i] = -1;
}
我做对了吗?还有其他方法可以做到吗?
Am i going correct? Is there any other way for the same?
推荐答案
如果是原始类型,则可以使用Arrays.fill()
:
If it's a primitive type, you can use Arrays.fill()
:
Arrays.fill(array, -1);
[顺便说一句,C或C ++中的memset
仅对char
数组真正有用.]
[Incidentally, memset
in C or C++ is only of any real use for arrays of char
.]
这篇关于如何在Java中将数组的所有元素初始化为任何特定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!