与 Collections.singletonList(something) 相比,使用 Arrays.asList(something) 来制作包含一个项目的列表是否有优势(或有很大的不同)?后者也使返回的列表不可变。
最佳答案
Collections.singletonList(something)
是 immutable 而 Arrays.asList(something)
是固定大小的 List
表示列表和数组在堆中连接的数组。
Arrays.asList(something)
允许对其进行非结构性更改,这会同时反射(reflect)到 List 和联合数组。它会抛出 UnsupportedOperationException
用于添加、删除元素,尽管您可以为特定索引设置元素。
对 Collections.singletonList(something)
返回的列表所做的任何更改都将导致 UnsupportedOperationException
。
此外,Collections.singletonList(something)
返回的 List 的容量将始终为 1,这与 Arrays.asList(something)
不同其容量将是支持数组的大小。
关于java - Arrays.asList() 与 Collections.singletonList(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26027396/