关于java:Arrays.asList()vs Collections.singletonList()

Arrays.asList() vs Collections.singletonList()

使用array.aslist(something)比使用collections.singletonlist(something)生成包含一个项的列表有什么好处(或很大的区别)?后者也使返回的列表不可变。


Collections.singletonList(something)是不可变的,而Arrays.asList(something)是一个固定大小的List表示的数组,其中列表和数组加入堆中。

Arrays.asList(something)允许对其进行非结构更改,这将同时反映到列表和连接数组中。它抛出UnsupportedOperationException来添加、删除元素,尽管您可以为特定索引设置元素。

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

另外,由Collections.singletonList(something)返回的列表的容量始终是1,而不像Arrays.asList(something),后者的容量将是备份数组的大小。


我要补充的是,singletonList没有数组支持,只是引用了那个项。据推测,它将占用更少的内存,并且根据您想要创建的列表的数量,它可能非常重要。


方法Arrays.asList返回由指定数组支持的固定大小列表。该方法返回ArrayList的一个实例,该实例是扩展AbstractList而不是java.util.ArrayList的私有嵌套静态类。这个静态类提供了一些方法的实现,例如set, indexOf, forEach, replaceAll等,但是当我们调用add时,它没有自己的实现,而是调用了AbstractList中的方法来抛出java.lang.UnsupportedOperationException

Collections.singletonList返回一个只包含指定对象的不可变列表,该列表也可以序列化。

另一方面,对于不可变列表,我们通常使用Collections.unmodifiableList,它返回指定列表的不可修改视图。

1
2
3
4
5
6
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

不可修改的视图集合是不可修改的集合,也是支持集合上的视图。请注意,对支持集合的更改可能仍然是可能的,如果发生更改,则可以通过不可修改的视图看到这些更改。

我们可以在Java 10和以后有一个真正不变的列表。有两种方法可以获得真正不可修改的列表:

  • var unmodifiableList = List.copyOf(srcList);=>打印苹果
  • var unmodifiableList = srcList.stream().collect(Collectors.toUnmodifiableList());=>打印苹果
  • 根据Java 10的DOC:

    The List.of and List.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 Form page.