简体   繁体   中英

Create an array with n copies of the same value/object?

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:

  1. it's nice and smooth,
  2. it consumes less memory (see source code ) which is significant for a huge copies amount or huge objects to copy,
  3. it creates an immutable list,
  4. 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]);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM