Any shortcut to initialize all array elements to zero?

后端 未结 14 2784
北恋
北恋 2020-11-28 18:12

In C/C++ I used to do

int arr[10] = {0};

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

Is there a similar shortcut in

14条回答
  •  生来不讨喜
    2020-11-28 18:27

    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 Arrays class:

    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:

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

    Would give arr the value:

    [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:

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

提交回复
热议问题