Any shortcut to initialize all array elements to zero?
In java all elements(primitive integer types byte
short
, int
, long
) are initialised to 0 by default. You can save the loop.
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);
A default value of 0 for arrays of integral types is guaranteed by the language spec:
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
.
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).