不可变与不可修改集合 [英] Immutable vs Unmodifiable collection

查看:43
本文介绍了不可变与不可修改集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自集合框架概述:

不支持修改操作(如addremoveclear)的集合被称为不可修改em>.不可修改的集合可修改.

Collections that do not support modification operations (such as add, remove and clear) are referred to as unmodifiable. Collections that are not unmodifiable are modifiable.

另外保证 Collection 对象中没有变化的集合被称为 不可变.不可变的集合可变.

Collections that additionally guarantee that no change in the Collection object will be visible are referred to as immutable. Collections that are not immutable are mutable.

我无法理解其中的区别.
这里的 unmodifiableimmutable 有什么区别?

I cannot understand the distinction.
What is the difference between unmodifiable and immutable here?

推荐答案

不可修改的集合通常是可修改集合的包装器其他代码可能仍然可以访问.因此,虽然如果您只有对不可修改集合的引用,不能对其进行任何更改,但您不能依赖内容不变.

An unmodifiable collection is often a wrapper around a modifiable collection which other code may still have access to. So while you can't make any changes to it if you only have a reference to the unmodifiable collection, you can't rely on the contents not changing.

不可变集合保证没有任何可以更改集合.如果它包装了一个可修改的集合,它会确保没有其他代码可以访问该可修改的集合.请注意,虽然没有代码可以更改集合包含对哪些对象的引用,但对象本身可能仍然是可变的 - 创建 StringBuilder 的不可变集合并不会以某种方式冻结"这些对象.

An immutable collection guarantees that nothing can change the collection any more. If it wraps a modifiable collection, it makes sure that no other code has access to that modifiable collection. Note that although no code can change which objects the collection contains references to, the objects themselves may still be mutable - creating an immutable collection of StringBuilder doesn't somehow "freeze" those objects.

基本上,区别在于其他代码是否能够更改您背后的集合.

Basically, the difference is about whether other code may be able to change the collection behind your back.

这篇关于不可变与不可修改集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆