如何将数组的所有元素初始化为java中的任何特定值 [英] How to initialize all the elements of an array to any specific value in java

查看:58
本文介绍了如何将数组的所有元素初始化为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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆