Arrays.asList() vs Collections.singletonList()
使用array.aslist(something)比使用collections.singletonlist(something)生成包含一个项的列表有什么好处(或很大的区别)?后者也使返回的列表不可变。
对
另外,由
我要补充的是,singletonList没有数组支持,只是引用了那个项。据推测,它将占用更少的内存,并且根据您想要创建的列表的数量,它可能非常重要。
方法
另一方面,对于不可变列表,我们通常使用
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和以后有一个真正不变的列表。有两种方法可以获得真正不可修改的列表:
根据Java 10的DOC:
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 Form page.
号