如何创建具有特定元素大小的列表 [英] How to create a list with specific size of elements

查看:58
本文介绍了如何创建具有特定元素大小的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比如说,我想快速创建一个包含 1000 个元素的列表.实现此目的的最佳方法是什么?

Say, I want to create a list quickly which contains 1000 elements. What is the best way to accomplish this?

推荐答案

您可以使用 Collections.nCopies.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆