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

后端 未结 7 1721
刺人心
刺人心 2020-12-16 11:29

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

7条回答
  •  无人及你
    2020-12-16 11:45

    List 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]);
    

提交回复
热议问题