google 的 ImmutableList 和 Collections.unmodifiableList() 有什么区别? [英] What is the difference between google's ImmutableList and Collections.unmodifiableList ()?

查看:30
本文介绍了google 的 ImmutableList 和 Collections.unmodifiableList() 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自 ImmutableList javadocs:

From ImmutableList javadocs:

不一样Collections.unmodifiableList(java.util.List),这是一个单独的视图仍然可以改变的集合,一个ImmutableList 的实例包含它的拥有私人数据,永远不会改变.ImmutableList 很方便对于公共静态最终列表(常量列表"),还可以让你轻松制作一个防御性副本"由您的班级提供的列表来电者.

Unlike Collections.unmodifiableList(java.util.List), which is a view of a separate collection that can still change, an instance of ImmutableList contains its own private data and will never change. ImmutableList is convenient for public static final lists ("constant lists") and also lets you easily make a "defensive copy" of a list provided to your class by a caller.

是否意味着:

  1. 如果我有 Dimension 对象的 ImmutableList(例如),那么我不能更改其中的任何 Dimension 对象?
  2. 如果我有 Dimension 对象的 Collections.unmodifiableList(列表),那么我不仅可以添加或删除任何对象,还可以更改它们(例如调用 setDimension(width, height) 方法)?

推荐答案

不,不变性只适用于Collection中对象的数量和引用,并没有解决您放入 Collection 中的对象.

No, the immutability is only applied to the amount and references of the objects in the Collection, and does not address the mutability of objects you put in the Collection.

与标准 JDK Collections.unmodifiableList 相比,Immutable 列表的优势在于,通过使用 ImmutableList,您可以保证引用的对象、它们的顺序和列表的大小不能从任何来源更改.使用 Collections.unmodifiableList 如果其他内容引用了底层列表,即使您引用了不可修改的列表,该代码也可以修改列表.

What Immutable list gains over the standard JDK Collections.unmodifiableList is that by using ImmutableList you are guaranteed that the objects referenced, their order and the size of the list cannot change from any source. With Collections.unmodifiableList if something else has a reference to the underlying list, that code can modify the list even though you have a reference to an unmodifiable list.

但是,如果您想要真正的不变性,则必须用不可变对象填充列表.

If, however, you want true immutability, you have to fill the list with immutable objects.

这篇关于google 的 ImmutableList 和 Collections.unmodifiableList() 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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