来自 Java 1.6 Collection Framework documentation :
Collections that do not support any modification operations (such as
add
,remove
andclear
) are referred to as unmodifiable. [...] Collections that additionally guarantee that no change in the Collection object will ever be visible are referred to as immutable.
第二个标准让我有点困惑。鉴于第一个集合是不可修改的,并且假设原始集合引用已被丢弃,那么第二行中提到的更改是什么?它是指集合中元素的变化,即元素的状态吗?
第二个问题:
对于不可变的集合,如何提供指定的额外保证?如果集合中元素的状态由线程更新,那么状态中的这些更新在持有不可变集合的线程上不可见就足以实现不变性吗?
要使集合不可变,如何提供指定的额外保证?
最佳答案
不可修改的集合通常是其他集合的只读 View (包装器)。您无法添加、删除或清除它们,但基础集合可以更改。
不可变集合根本无法更改 - 它们不包装另一个集合 - 它们有自己的元素。
这里引用 Guava 的 ImmutableList
Unlike
Collections.unmodifiableList(java.util.List<? extends T>)
, which is a view of a separate collection that can still change, an instance ofImmutableList
contains its own private data and will never change.
因此,基本上,为了从可变集合中获取不可变集合,您必须将其元素复制到新集合中,并禁止所有操作。
关于Java 不可变集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7713274/