问题
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