我们能够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);),我们就可以自由地改变对象.
不可变列表中的项目没有不变性保证.它们和往常一样可变.
是的,该java.util.List变量是可变的,并且不会List在add()或上创建另一个实例remove()。
如果您要查找不可变列表,请检查ImmutableList或Collections.unmodifiableList的Guava实现,这些实现会引发修改。java.lang.UnsupportedOperationException
是.这是可变的.如果你想拥有一个不可变的,你可以使用java实用程序集合类来包装它:java.util.Collections #unmodifiableList
像这样:
List<Object> mutableList = new ArrayList<>();
List<Object> immutableList = Collections.unmodifiableList(mutableList);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12849 次 |
| 最近记录: |