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

arrays, java

Solution

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`.]

Problem

In C and C++ we have the `memset()` function which can fulfill my wish. But in Java, how can I initialize all the elements to a specific value? Whenever we write `int[] array = new int[10]`, this simply initializes an array of size 10 having all elements set to 0, but I just want to initialize all elements to something other than 0 (say, `-1`). Otherwise I have to put a `for` loop just after the initialization, which ranges from index 0 to index size − 1, and inside that loop assign each element to the desired value, like this: ``` int[] array = new int[10]; for (int i = 0; i < array.length; i++) { array[i] = -1; } ``` Am I going correct? Is there any other way to do this?

Original source

Related problems