Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collections.nCopies() vs. For-loop Initialization

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?

like image 801
Omar Abdeldayem Avatar asked Aug 31 '13 01:08

Omar Abdeldayem


1 Answers

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.

like image 93
Sergey Kalinichenko Avatar answered Sep 19 '22 04:09

Sergey Kalinichenko