I want to create an array of size n
with the same value at every index in the array. What\'s the best way to do this in Java?
For example, if n
Or you can do it in the low level way. Make an array with n elements and iterate through all the element where the same element is put in.
int[] array = new int[n];
for (int i = 0; i < n; i++)
{
array[i] = 5;
}
For that specific example, nothing, a boolean[]
will be initialised to [false, false, ...]
by default.
If you want to initialise your array with non-default values, you will need to loop or use Arrays.fill
which does the loop for you.
List<Integer> copies = Collections.nCopies(copiesCount, value);
javadoc here.
This is better than the 'Arrays.fill' solution by several reasons:
And lists are cooler than arrays :) But if you really-really-really want an array – then you can do the following:
Integer[] copies = Collections.nCopies(copiesCount, value)
.toArray(new Integer[copiesCount]);
Arrays.fill() will fill an existing array with the same value. Variants exist for primitives and Objects
.
try this ..
Boolean [] data = new Boolean[20];
Arrays.fill(data,new Boolean(false));
Arrays.fill(...) is what you are looking for.