如何创建具有特定元素大小的列表 [英] How to create a list with specific size of elements
问题描述
说,我想快速创建一个包含1000个元素的列表.最好的方法是什么?
Say, I want to create a list quickly which contains 1000 elements. What is the best way to accomplish this?
推荐答案
You can use Collections.nCopies
.
但是请注意,返回的列表是不可变的.实际上,文档说:"新分配的数据对象很小(它包含对数据对象的单个引用)".
Note however that the list returned is immutable. In fact, the docs says "it the newly allocated data object is tiny (it contains a single reference to the data object)".
如果您需要可变列表,则可以执行类似的操作
If you need a mutable list, you would do something like
List<String> hellos = new ArrayList<String>(Collections.nCopies(1000, "Hello"));
如果需要1000个不同的对象,则可以使用
If you want 1000 distinct objects, you can use
List<YourObject> objects = Stream.generate(YourObject::new)
.limit(1000)
.collect(Collectors.toList());
同样,不能保证结果列表实现的功能.如果需要,请说一个 ArrayList
,
Again, there is not guarantees about the capabilities of the resulting list implementation. If you need, say an ArrayList
, you would do
...
.collect(ArrayList::new);
这篇关于如何创建具有特定元素大小的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!