Arrays.asList() | mutable |
Collection.emptyList() | immutable |
Collections.singletonList() | immutable |
Arrays.asList() is not immutable
Collections.singletonList() 是建单个元素的列表,并且建出来的List是immutable(不可变的),就是初始化之后不能再加元素。
Using Collections.singletonList() Method [ Immutable List ]
This is simplest and recommended method to create immutable List with single element inside it. The list created with this method is immutable as well, so you are sure that there will not be any more elements in list, at any condition.
List list = Collections.singletonList( "data" ); //How to create
https://cloud.tencent.com/developer/article/1670444
如果尝试对 List 中的元素进行增加、删除或者更新,就会抛出 UnsupportedOperationException 异常。
另外,Immutable List 中的元素是非 null 的,如果使用 null 来创建 Immutable List,则会抛出 NullPointerException;如果尝试在 Immutable List 中添加 null 元素,则会抛出 UnsupportedOperationException。
那 Immutable List 有什么好处呢?