Java Arrays.asList() 与 Collections.singletonList()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26027396/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Arrays.asList() vs Collections.singletonList()
提问by Howard Grimberg
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) 相比,使用 Arrays.asList(something) 制作包含一个项目的列表是否有优势(或有很大不同)?后者也使返回的列表不可变。
采纳答案by Kumar Abhinav
Collections.singletonList(something)
is immutablewhereas Arrays.asList(something)
is a fixed size List
representation of an Array where the List and Array gets joined in the heap.
Collections.singletonList(something)
是不可变的,而是ArrayArrays.asList(something)
的固定大小List
表示,其中 List 和 Array 在堆中连接。
Arrays.asList(something)
allows non-structural changesmade 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.
Arrays.asList(something)
允许对其进行非结构性更改,这会反映到 List 和连接数组。UnsupportedOperationException
尽管您可以为特定索引设置元素,但它会抛出添加、删除元素。
Any changes made to the List returned by Collections.singletonList(something)
will result in UnsupportedOperationException
.
对返回的列表所做的任何更改都Collections.singletonList(something)
将导致UnsupportedOperationException
.
Also, the capacity of the List returned by Collections.singletonList(something)
will always be 1unlike Arrays.asList(something)
whose capacity will be the size of the backed array.
此外,返回的 List 的容量Collections.singletonList(something)
将始终为1,而Arrays.asList(something)
其容量将是支持数组的大小。
回答by apprentice
I would just add that the singletonlist is not backed by an array and just has a reference to that one item. Presumably, it would take less memory and can be significant depending on the number of lists you want to create.
我只想补充一点,singletonlist 没有由数组支持,只有对那一项的引用。据推测,它会占用更少的内存,并且可能很重要,具体取决于您要创建的列表数量。
回答by akhil_mittal
The method Arrays.asList
returns a fixed-size list backed by the specified array. The method returns an instance of ArrayList
which is a private nested static classextending AbstractList
and not java.util.ArrayList
. This static class provides implementation of few methods e.g. set, indexOf, forEach, replaceAll
etc. but when we invoke add
it has no implementation of its own, rather method from AbstractList
is invoked which throws java.lang.UnsupportedOperationException
.
该方法Arrays.asList
返回由指定数组支持的固定大小列表。该方法返回一个实例,ArrayList
它是一个私有嵌套静态类扩展AbstractList
而不是java.util.ArrayList
。这个静态类提供了一些方法的实现,例如set, indexOf, forEach, replaceAll
等,但是当我们调用add
它时,它没有自己的实现,而是AbstractList
调用了抛出的方法 from java.lang.UnsupportedOperationException
。
The Collections.singletonList
returns an immutable listcontaining only the specified object and it is serializable as well.
所述Collections.singletonList
返回一个不可变列表仅包含指定的对象,这是可序列化的为好。
On a side note, for immutable listswe generally use Collections.unmodifiableList
which returns an unmodifiable view of the specified list.
附带说明一下,对于不可变列表,我们通常使用Collections.unmodifiableList
它返回指定列表的不可修改视图。
List<String> srcList = Arrays.asList("Apple", "Mango", "Banana");
var fruits = new ArrayList<>(srcList);
var unmodifiableList = Collections.unmodifiableList(fruits);
fruits.set(0, "Apricot");
var modFruit = unmodifiableList.get(0);
System.out.println(modFruit); // prints Apricot
An unmodifiable view collection is a collection that is unmodifiable and is also a view onto a backing collection. Note that changes to the backing collection might still be possible, and if they occur, they are visible through the unmodifiable view.
不可修改的视图集合是不可修改的集合,也是支持集合的视图。请注意,对后备集合的更改可能仍然是可能的,如果发生更改,它们将通过不可修改的视图可见。
We can have a true immutable list in Java 10and later. There are two ways to get truly unmodifiable list:
我们可以在Java 10及更高版本中拥有一个真正的不可变列表。有两种方法可以获得真正不可修改的列表:
var unmodifiableList = List.copyOf(srcList);
var unmodifiableList = srcList.stream().collect(Collectors.toUnmodifiableList());
If any of these two variables are used value will still be "Apple" and not "Apricot".
var unmodifiableList = List.copyOf(srcList);
var unmodifiableList = srcList.stream().collect(Collectors.toUnmodifiableList());
如果使用这两个变量中的任何一个,值仍然是“Apple”而不是“Apricot”。
As per docof Java 10:
按照文档的Java的10:
The
List.of
andList.copyOf
static factory methods provide a convenient way to create unmodifiable lists. The List instances created by these methods have the following characteristics:
- They are unmodifiable. Elements cannot be added, removed, or replaced. Calling any mutator method on the List will always cause
UnsupportedOperationException
to be thrown. However, if the contained elements are themselves mutable, this may cause the List's contents to appear to change.- They disallow null elements. Attempts to create them with null elements result in
NullPointerException
.- They are serializable if all elements are serializable.
- The order of elements in the list is the same as the order of the provided arguments, or of the elements in the provided array.
- They are
value-based
. Callers should make no assumptions about the identity of the returned instances. Factories are free to create new instances or reuse existing ones. Therefore, identity-sensitive operations on these instances (reference equality (==), identity hash code, and synchronization) are unreliable and should be avoided.- They are serialized as specified on the Serialized Formpage.
在
List.of
和List.copyOf
静态工厂方法提供了一种方便的方式来创建不可修改的列表。这些方法创建的 List 实例具有以下特点:
- 它们是不可修改的。不能添加、删除或替换元素。调用 List 上的任何 mutator 方法将始终导致
UnsupportedOperationException
抛出。但是,如果包含的元素本身是可变的,这可能会导致 List 的内容发生变化。- 它们不允许空元素。尝试使用空元素创建它们会导致
NullPointerException
.- 如果所有元素都可序列化,则它们是可序列化的。
- 列表中元素的顺序与提供的参数或提供的数组中元素的顺序相同。
- 他们是
value-based
。调用者不应假设返回实例的身份。工厂可以自由地创建新实例或重用现有实例。因此,对这些实例的身份敏感操作(引用相等 (==)、身份哈希码和同步)是不可靠的,应该避免。- 它们按照“序列化表单”页面上的指定进行序列化。