Collections.nCopies()与循环初始化 [英] Collections.nCopies() vs. For-loop Initialization

查看:343
本文介绍了Collections.nCopies()与循环初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近发现,可以通过调用 Collections.nCopies()方法而不是使用for循环来初始化Java中的列表。但这让我感到奇怪,在for循环中使用此方法是否有性能优势/劣势,还是做同一件事的简单方法?

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?

推荐答案

由于 nCopies 返回的集合是不可变的,因此此集合不必物化。换句话说,只需要一个空间来存放 T 类型的单个对象;其他所有操作都是集合接口的实现,该接口伪装为具有 N 个对象的集合,但实际上只有一个对象返回了 N 次。

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.

当您创建的集合很大时,这可能会为您提供很大的空间改进:实际上,收藏,与使用 for 循环初始化的真实收藏相比,您的节省就更大。

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.

这篇关于Collections.nCopies()与循环初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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