从集合框架概述:
不支持修改操作(如添加、删除和清除)的集合被称为不可修改的。不是不可修改的集合是可修改的。 另外保证Collection对象中的任何更改都不可见的集合称为不可变集合。不是不可变的集合是可变的。
我不明白其中的区别。 这里unmodifiable和immutable的区别是什么?
从集合框架概述:
不支持修改操作(如添加、删除和清除)的集合被称为不可修改的。不是不可修改的集合是可修改的。 另外保证Collection对象中的任何更改都不可见的集合称为不可变集合。不是不可变的集合是可变的。
我不明白其中的区别。 这里unmodifiable和immutable的区别是什么?
当前回答
[不可更改和不可更改]
不可修改的集合(对象)仍然可以通过改变原始对象来改变。使用参考是可能的。
Java提供了几种方法来创建一个不可修改的映射:
Collections.unmodifiableMap () Java 9 Map.of(), Map.ofEntries()
其他回答
如果我们讨论的是JDK不可修改*和番石榴不可修改*,实际上它们的区别还在于性能。如果不可变集合不是常规集合的包装器(JDK实现就是包装器),那么它们可以更快、更节省内存。 以番石榴团队为例:
JDK提供了集合。不可修改的xxx方法,但在我们看来,这些可以
<…>
低效:数据结构仍然有可变集合的所有开销,包括并发修改检查,哈希表中的额外空间等。
不可修改的集合通常是其他代码仍然可以访问的可修改集合的包装器。因此,如果您仅拥有对不可修改集合的引用,则不能对其进行任何更改,但不能指望内容不会更改。
不可变集合保证没有任何东西可以再改变集合。如果它包装了一个可修改的集合,它将确保没有其他代码可以访问该可修改的集合。注意,尽管没有代码可以改变集合包含引用的对象,但对象本身仍然可能是可变的——创建一个不可变的StringBuilder集合并不会以某种方式“冻结”那些对象。
基本上,区别在于其他代码是否能够在您背后更改集合。
引用Java™教程:
Unlike synchronization wrappers, which add functionality to the wrapped collection, the unmodifiable wrappers take functionality away. In particular, they take away the ability to modify the collection by intercepting all the operations that would modify the collection and throwing an UnsupportedOperationException. Unmodifiable wrappers have two main uses, as follows: To make a collection immutable once it has been built. In this case, it's good practice not to maintain a reference to the backing collection. This absolutely guarantees immutability. To allow certain clients read-only access to your data structures. You keep a reference to the backing collection but hand out a reference to the wrapper. In this way, clients can look but not modify, while you maintain full access.
(强调我的)
这真的很概括。
// normal list
List list1 = new ArrayList();
list1.add(1);
// unmodifiable list
List list2 = Collections.unmodifiableList(list1);
// immutable list
List list3 = Collections.unmodifiableList(new ArrayList<>(list1));
list1.add(2);
list1.add(3);
System.out.println(list1);
System.out.println(list2);
System.out.println(list3);
输出:
[1, 2, 3]
[1, 2, 3]
[1]
Java™教程介绍了以下内容:
Unlike synchronization wrappers, which add functionality to the wrapped collection, the unmodifiable wrappers take functionality away. In particular, they take away the ability to modify the collection by intercepting all the operations that would modify the collection and throwing an UnsupportedOperationException. Unmodifiable wrappers have two main uses, as follows: To make a collection immutable once it has been built. In this case, it's good practice not to maintain a reference to the backing collection. This absolutely guarantees immutability. To allow certain clients read-only access to your data structures. You keep a reference to the backing collection but hand out a reference to the wrapper. In this way, clients can look but not modify, while you maintain full access.
我认为这是一个很好的解释,足以理解其中的区别。