int num[5] = {1, 1, 1, 1, 1}; This will initialize the num array with value 1 at all index. The array will be initialized to 0 in case we provide empty initializer list or just specify 0 in the initializer list. Designated Initializer: This initializer is used when we want to initialize a range with the same value.
We can declare and initialize arrays in Java by using a new operator with an array initializer. Here's the syntax: Type[] arr = new Type[] { comma separated values }; For example, the following code creates a primitive integer array of size 5 using a new operator and array initializer.
int arr[10] = {0}; ...to initialize all my array elements to 0.
If it's a primitive type, you can use Arrays.fill()
:
Arrays.fill(array, -1);
[Incidentally, memset
in C or C++ is only of any real use for arrays of char
.]
There's also
int[] array = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1};
It is also possible with Java 8 streams:
int[] a = IntStream.generate(() -> value).limit(count).toArray();
Probably, not the most efficient way to do the job, however.
You could do this if it's short:
int[] array = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};
but that gets bad for more than just a few.
Easier would be a for
loop:
int[] myArray = new int[10];
for (int i = 0; i < array.length; i++)
myArray[i] = -1;
Edit: I also like the Arrays.fill()
option other people have mentioned.
java.util.Arrays.fill()
Have you tried the Arrays.fill function?
You can use Arrays.fill(array, -1)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With