How to create a list with specific size of elements

半世苍凉 提交于 2021-02-07 13:27:38

问题


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


回答1:


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

If you want 1000 distinct objects, you can use

List<YourObject> objects = Stream.generate(YourObject::new)
                                 .limit(1000)
                                 .collect(Collectors.toList());

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



回答2:


Fastest : int[] myList = new int[1000] will contain 1000 elements equal to zero. But I'm sure it doesn't suit your needs. Tell us more of what you need and I might be able to help :)



来源:https://stackoverflow.com/questions/8267348/how-to-create-a-list-with-specific-size-of-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!