java.util.List是否可变?

Vin*_*ran -1 java

我们能够add/ remove元素List使用add()/ remove()方法而不创建看起来类似的另一个列表StringBuffer append().所以我认为List是可变的.谁能证实我的理解是正确的?如果有错,请用下面的代码说明

List<String> strList = new ArrayList<String>();
strList.add("abc");
strList.add("xyz"); 
Run Code Online (Sandbox Code Playgroud)

Bir*_*abs 16

列出可变性

由于List是一个界面,它唯一的承诺是:"这些是你将获得的方法".

List接口描述了一个可变的 List.请注意,它具有的功能,如add(),set()remove().但请注意,这些mutator被指定为"可选"操作.

存在List接口的实现,其实际上是不可变的.

List<Integer> mutable = new ArrayList<>();
mutable.add(1);

List<Integer> immutable = Collections.unmodifiableList(mutable);
// try to modify the list
immutable.add(2);
// Exception in thread "main" java.lang.UnsupportedOperationException
Run Code Online (Sandbox Code Playgroud)

Collections.unmodifiableList()返回的实例List实现Collections.UnmodifiableList.

Collections.UnmodifiableList将所有不可变 List函数调用转发到底层函数List.而它通过抛出实现所有可变 List功能java.lang.UnsupportedOperationException.

列出元素可变性

如果我们这样做:

List<Date> mutable = new ArrayList<>();
dates.add(new Date());
List<Date> immutable = Collections.unmodifiableList(mutable);
Date myCoolDate = immutable.get(0);
Run Code Online (Sandbox Code Playgroud)

我们可以改变myCoolDate吗?绝对.

myCoolDate.setTime(99999); // works! mutates the original Date object in the `List`.
Run Code Online (Sandbox Code Playgroud)

List-无论是不可改变或以其他方式-存储对象的引用的副本.一旦我们引用了object(Date myCoolDate = immutable.get(0);),我们就可以自由地改变对象.

不可变列表中的项目没有不变性保证.它们和往常一样可变.


Yur*_*kov 6

是的,该java.util.List变量是可变的,并且不会Listadd()或上创建另一个实例remove()

如果您要查找不可变列表,请检查ImmutableListCollections.unmodifiableList的Guava实现,这些实现会引发修改。java.lang.UnsupportedOperationException


dve*_*opp 6

是.这是可变的.如果你想拥有一个不可变的,你可以使用java实用程序集合类来包装它:java.util.Collections #unmodifiableList

像这样:

  List<Object> mutableList = new ArrayList<>();
  List<Object> immutableList = Collections.unmodifiableList(mutableList);
Run Code Online (Sandbox Code Playgroud)

  • 我发现这个答案令人困惑,接近于误导。据我了解,问题是“List”是否可变。你展示了一个例子,其中有的地方是,有的地方没有。这些例子是正确的,所以我当然不会说“是的。” 它是可变的”。 (2认同)