问题
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]
回答1:
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};
回答2:
List<Integer> copies = Collections.nCopies(copiesCount, value);
javadoc here.
This is better than the 'Arrays.fill' solution by several reasons:
- it's nice and smooth,
- it consumes less memory (see source code) which is significant for a huge copies amount or huge objects to copy,
- it creates an immutable list,
- it can create a list of copies of an object of a non-primitive type. That should be used with caution though because the element itself will not be duplicated and get() method will return the same value for every index. It's better to provide an immutable object for copying or make sure it's not going to be changed.
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]);
回答3:
Arrays.fill() will fill an existing array with the same value. Variants exist for primitives and Objects.
回答4:
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.
回答5:
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;
}
回答6:
Arrays.fill(...) is what you are looking for.
回答7:
try this ..
Boolean [] data = new Boolean[20];
Arrays.fill(data,new Boolean(false));
来源:https://stackoverflow.com/questions/14276470/create-an-array-with-n-copies-of-the-same-value-object