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
is 5 and the value is the boolean false
, the array should be:
= [false, false, false, false, false]
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]);
You can try it with:
boolean[] array = new boolean[5];
Arrays.fill(array, false);
Second method with manual array fill:
boolean[] array = new boolean[] {false, false, false, false, false};
Arrays.fill() will fill an existing array with the same value. Variants exist for primitives and Objects
.
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.
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;
}
Arrays.fill(...)
是您要寻找的。
try this ..
Boolean [] data = new Boolean[20];
Arrays.fill(data,new Boolean(false));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.