简体   繁体   English

创建具有n个相同值/对象的副本的数组?

[英]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. 我想创建一个大小为n的数组,在数组的每个索引处都使用相同的值。 What's the best way to do this in Java? 用Java做到这一点的最佳方法是什么?

For example, if n is 5 and the value is the boolean false , the array should be: 例如,如果n为5且值为boolean false ,则数组应为:

= [false, false, false, false, false]
List<Integer> copies = Collections.nCopies(copiesCount, value);

javadoc here . javadoc 在这里

This is better than the 'Arrays.fill' solution by several reasons: 由于以下几个原因,这比“ Arrays.fill”解决方案要好:

  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. 但是应谨慎使用,因为元素本身不会被复制,并且get()方法将为每个索引返回相同的值。 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. Arrays.fill()将使用相同的值填充现有数组。 Variants exist for primitives and Objects . 存在图元和Objects变体。

For that specific example, nothing, a boolean[] will be initialised to [false, false, ...] by default. 对于该特定示例,什么也没有,默认情况下, boolean[]将被初始化为[false, false, ...]

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. 如果要使用非默认值初始化数组,则需要循环或使用Arrays.fill为您执行循环。

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. 创建一个包含n个元素的数组,并遍历放置相同元素的所有元素。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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