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
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
In c/cpp there is no shortcut but to initialize all the arrays with the zero subscript.Ex:
int arr[10] = {0};
But in java there is a magic tool called Arrays.fill() which will fill all the values in an array with the integer of your choice.Ex:
import java.util.Arrays;
public class Main
{
public static void main(String[] args)
{
int ar[] = {2, 2, 1, 8, 3, 2, 2, 4, 2};
Arrays.fill(ar, 10);
System.out.println("Array completely filled" +
" with 10\n" + Arrays.toString(ar));
}
}
Yet another approach by using lambda above java 8
Arrays.stream(new Integer[nodelist.size()]).map(e ->
Integer.MAX_VALUE).toArray(Integer[]::new);
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);
In java all elements(primitive integer types byte
short
, int
, long
) are initialised to 0 by default. You can save the loop.
You can save the loop, initialization is already made to 0. Even for a local variable.
But please correct the place where you place the brackets, for readability (recognized best-practice):
int[] arr = new int[10];