UnsupportedOperationException

UnsupportedOperationException

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

问题描述

与 Collections.singletonList(something) 相比,使用 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)immutableArrays.asList(something) 是一个固定大小的 List 表示,其中 List 和 Array 在堆中连接.

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) 允许对其进行非结构性更改,这会反映到 List 和联合数组中.它会抛出 UnsupportedOperationException 以添加、删除元素,尽管您可以为特定索引设置元素.

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.

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

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

此外,Collections.singletonList(something) 返回的 List 的容量将始终为 1Arrays.asList(something) 不同其容量将是支持数组的大小.

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() 与 Collections.singletonList()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 21:33