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

后端 未结 7 1713
刺人心
刺人心 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:42

    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;
    }
    
    0 讨论(0)
  • 2020-12-16 11:44

    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.

    0 讨论(0)
  • 2020-12-16 11:45
    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]);
    
    0 讨论(0)
  • 2020-12-16 11:48

    Arrays.fill() will fill an existing array with the same value. Variants exist for primitives and Objects.

    0 讨论(0)
  • 2020-12-16 11:53

    try this ..

     Boolean [] data = new Boolean[20];
      Arrays.fill(data,new Boolean(false));
    
    0 讨论(0)
  • 2020-12-16 11:55

    Arrays.fill(...) is what you are looking for.

    0 讨论(0)
提交回复
热议问题