Reputation: 6328
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?
Upvotes: 141
Views: 313499
Reputation: 9
Arrays class in java.utils has a method for that.
Arrays.fill(your_array, value_to_fill);
Upvotes: 0
Reputation: 9903
Using Java 8, you can simply use ncopies
of Collections
class:
Object[] arrays = Collections.nCopies(size, object).stream().toArray();
In your case it will be:
Integer[] arrays = Collections.nCopies(10, Integer.valueOf(1)).stream().toArray(Integer[]::new);
.
Here is a detailed answer of a similar case of yours.
Upvotes: 1
Reputation: 793
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.
Upvotes: 3
Reputation: 9447
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.
Upvotes: 8
Reputation: 1657
Evidently you can use Arrays.fill(), The way you have it done also works though.
Upvotes: 0
Reputation: 272517
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
.]
Upvotes: 265
Reputation: 51445
There's also
int[] array = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1};
Upvotes: 31