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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2154251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 04:11:06  来源:igfitidea点击:

Any shortcut to initialize all array elements to zero?

java

提问by gameover

In C/C++I used to do

C/C++我以前做的

int arr[10] = {0};

...to initialize all my array elements to 0.

...将我的所有数组元素初始化为 0。

Is there a similar shortcut in Java?

Java中是否有类似的快捷方式?

I want to avoid using the loop, is it possible?

我想避免使用循环,这可能吗?

int arr[] = new int[10];
for(int i = 0; i < arr.length; i++) {
    arr[i] = 0;
}

采纳答案by Michael Borgwardt

A default value of 0 for arrays of integral types is guaranteed by the language spec:

语言规范保证整数类型数组的默认值为 0 :

Each class variable, instance variable, or array component is initialized with a default valuewhen it is created (§15.9, §15.10) [...] For type int, the default value is zero, that is, 0.  

每个类变量、实例变量或数组组件在创建时都会使用默认值进行初始化(第 15.9 节、第 15.10 节)[...] 对于 type int,默认值为零,即0.  

If you want to initialize an one-dimensional array to a different value, you can use java.util.Arrays.fill()(which will of course use a loop internally).

如果您想将一维数组初始化为不同的值,您可以使用java.util.Arrays.fill()(这当然会在内部使用循环)。

回答by Arne Deutsch

In java all elements are initialised to 0 by default. You can save the loop.

在 java 中,默认情况下所有元素都初始化为 0。您可以保存循环。

回答by KLE

You can save the loop, initialization is already made to 0. Even for a local variable.

您可以保存循环,初始化已经为 0。即使是局部变量。

But please correct the place where you place the brackets, for readability (recognized best-practice):

但请更正您放置括号的位置,以提高可读性(公认的最佳实践):

int[] arr = new int[10];

回答by Adam Parkin

While the other answers are correct (int array values are by default initialized to 0), if you wanted to explicitly do so (say for example if you wanted an array filled with the value 42), you can use the fill() method of the Arraysclass:

虽然其他答案是正确的(默认情况下 int 数组值初始化为 0),但如果您想明确这样做(例如,如果您想要一个用值 42 填充的数组),您可以使用 fill() 方法该数组类:

int [] myarray = new int[num_elts];
Arrays.fill(myarray, 42);

Or if you're a fan of 1-liners, you can use the Collections.nCopies()routine:

或者,如果您是 1-liners 的粉丝,则可以使用以下Collections.nCopies()例程:

Integer[] arr = Collections.nCopies(3, 42).toArray(new Integer[0]);

Would give arr the value:

会给 arr 值:

[42, 42, 42]

(though it's Integer, and not int, if you need the primitive type you could defer to the Apache Commons ArrayUtils.toPrimitive()routine:

(尽管它是Integer,而不是int,如果您需要原始类型,您可以遵循Apache CommonsArrayUtils.toPrimitive()例程:

int [] primarr = ArrayUtils.toPrimitive(arr);

回答by Jugal Thakkar

How it Reduces the Performance of your application....? Read Following.

它如何降低应用程序的性能....?阅读以下内容。

In Java Language Specification the Default / Initial Valuefor any Object can be given as Follows.

在 Java 语言规范中,任何对象的默认值/初始值都可以如下给出。

For type byte, the default valueis zero, that is, the value of (byte) is 0.

对于类型字节,所述默认值,即,(字节)的值是0

For type short, the default valueis zero, that is, the value of (short) is 0.

对于类型,所述默认值,即,(短)的值是0

For type int, the default valueis zero, that is, 0.

对于类型INT,所述默认值,即,0

For type long, the default valueis zero, that is, 0L.

对于类型时,默认值,也就是0L

For type float, the default valueis positive zero, that is, 0.0f.

对于类型浮子,该默认值正零,即,0.0F

For type double, the default valueis positive zero, that is, 0.0d.

对于类型,则默认值正零,也就是0.0D

For type char, the default valueis the nullcharacter, that is, '\u0000'.

对于类型字符,则默认值字符,也就是“ \ u0000的”。

For type boolean, the default valueis false.

对于类型布尔型,则默认值假的

For all reference types, the default valueis null.

对于所有引用类型默认值

By Considering all this you don't need to initialize with zero values for the array elements because by default all array elements are 0 for int array.

通过考虑所有这些,您不需要为数组元素初始化零值,因为默认情况下所有数组元素对于 int 数组都是 0。

Because An arrayis a container object that holds a fixed number of values of a single type. Now the Type of array for you is intso consider the default value for all array elements will be automatically 0Because it is holding int type.

因为数组是一个容器对象,它包含固定数量的单一类型的值。现在你的数组类型是int所以考虑所有数组元素的默认值将自动为 0因为它持有 int type

Now considerthe arrayfor String typeso that all array elements has default valueis null.

现在考虑阵列字符串类型,使所有的数组元素具有默认值

Why don't do that......?

为什么不这样做......?

you can assign null value by using loop as you suggest in your Question.

您可以按照您在问题中的建议使用循环分配空值。

int arr[] = new int[10];
for(int i=0;i<arr.length;i++)
    arr[i] = 0;

But if you do so then it will an useless loss of machine cycle. and if you use in your application where you have many arrays and you do that for each array then it will affect the Application Performance up-to considerable level.

但是如果你这样做了,那将是一个无用的机器周期损失。如果您在具有许多阵列的应用程序中使用,并且对每个阵列都这样做,那么它将影响应用程序性能到相当大的水平。

The more use of machine cycle ==>More time to Process the data ==> Output time will be significantly increase. so that your application data processing can be considered as a low level(Slow up-to some Level).

机器周期使用越多==>处理数据的时间越长==> 输出时间将显着增加。以便您的应用程序数据处理可以被视为低级别(Slow up-to some Level)。

回答by Pankaj Goyal

If you are using Float or Integer then you can assign default value like this ...

如果您使用的是浮点数或整数,那么您可以像这样分配默认值...

Integer[] data = new Integer[20];
Arrays.fill(data,new Integer(0));

回答by Dhruvam Gupta

declare the array as instance variable in the class i.e. out of every method and JVM will give it 0 as default value. You need not to worry anymore

将数组声明为类中的实例变量,即在每个方法之外,JVM 将给它 0 作为默认值。你不必再担心了

回答by nate

Yes, int values in an array are initialized to zero. But you are not guaranteed this. Oracle documentation states that this is a bad coding practice.

是的,数组中的 int 值被初始化为零。但你不能保证这一点。Oracle 文档指出这是一种糟糕的编码实践。

回答by Kavishankar Karunakaran

You can create a new empty array with your existing array size, and you can assign back them to your array. This may faster than other. Snipet:

您可以使用现有数组大小创建一个新的空数组,并且可以将它们分配回您的数组。这可能比其他更快。片段:

package com.array.zero;
public class ArrayZero {
public static void main(String[] args) {
    // Your array with data
    int[] yourArray = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    //Creating same sized array with 0
    int[] tempArray = new int[yourArray.length];
    Assigning temp array to replace values by zero [0]
    yourArray = tempArray;

    //testing the array size and value to be zero
    for (int item : yourArray) {
        System.out.println(item);
    }
}
}

Result :

结果 :

0
0
0
0
0    
0
0
0
0

回答by Ubeyd

    int a=7, b=7 ,c=0,d=0;
    int dizi[][]=new int[a][b];
    for(int i=0;i<a;i++){
        for(int q=d;q<b;q++){
            dizi[i][q]=c;               
            System.out.print(dizi[i][q]);
            c++;
        }

        c-=b+1;
        System.out.println();               
    }

result 0123456 -1012345 -2-101234 -3-2-10123 -4-3-2-1012 -5-4-3-2-101 -6-5-4-3-2-10

结果 0123456 -1012345 -2-101234 -3-2-10123 -4-3-2-1012 -5-4-3-2-101 -6-5-4-3-2-10