Arrays.asList()vs Collections.singletonList() [英] Arrays.asList() vs Collections.singletonList()

查看:1904
本文介绍了Arrays.asList()vs Collections.singletonList()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Arrays.asList(something)而不是Collections.singletonList(something)来创建一个包含一个项目的列表有一个优点(或许多差别)?

Collections.singletonList(something) immutable ,而 Arrays.asList(something)是固定大小 List 数组的表示,其中列表和数组在堆中连接。



Arrays.asList(something)允许对其进行非结构更改它被反映到List和联合数组。它会添加 UnsupportedOperationException ,虽然您可以为特定索引设置元素。



Collections.singletonList(something)返回的列表所做的任何更改将导致 UnsupportedOperationException



此外, Collections.singletonList(something)返回的List的容量总是 1 c> Arrays.asList(something),其容量将是所支持数组的大小。


Is there an advantage (or much of a difference) to using Arrays.asList(something) over Collections.singletonList(something) to make a list containing one item? The latter makes the returned list immutable as well.

解决方案

Collections.singletonList(something) is immutable whereas Arrays.asList(something) is a fixed size List representation of an Array where the List and Array gets joined in the heap.

Arrays.asList(something) allows non-structural changes made to it, which gets reflected to both the List and the conjoined array. It throws UnsupportedOperationException for adding, removing elements although you can set an element for a particular index.

Any changes made to the List returned by Collections.singletonList(something) will result in UnsupportedOperationException.

Also, the capacity of the List returned by Collections.singletonList(something) will always be 1 unlike Arrays.asList(something) whose capacity will be the size of the backed array.

这篇关于Arrays.asList()vs Collections.singletonList()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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