Collections.nCopies() vs. For-loop Initialization

可紊 提交于 2020-08-07 04:03:52

问题


I recently found out that you can initialize Lists in Java by calling the Collections.nCopies()method rather than using a for-loop. But that got me wondering, is there a performance advantage/disadvantage in using this method over a for-loop or is it just a simpler way of doing the same thing?


回答1:


Since the collection returned by nCopies is immutable, the entries in this collection need not be "materialized". In other words, all that is needed is a space for a single object of type T; everything else is an implementation of the collection interface that pretends to have a collection of N objects, but in reality has only one object that it returns N times.

This may prove to give you a lot of improvement in space when the collection you are creating is large: in fact, the larger the collection, the bigger is your savings compared to a real collection that you initialize with a for loop.




回答2:


Immutability is not an issue when you are using nCopies() as the argument to a List constructor: the constructor creates a copy, which is not immutable.



来源:https://stackoverflow.com/questions/18543473/collections-ncopies-vs-for-loop-initialization

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