Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize all the elements of an array to any specific value in java

Tags:

java

arrays

People also ask

How do you initialize an entire array with value?

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.

How do you initialize an entire array in Java?

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.

How do you assign a zero to all elements of an array in Java?

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).