Collections.unmodifiableSet()和Guava的ImmutableSet有什么区别? [英] What's the difference between Collections.unmodifiableSet() and ImmutableSet of Guava?

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

问题描述

ImmutableSet 的JavaDoc说:

JavaDoc of ImmutableSet says:


与<$ c不同$ c> Collections.unmodifiableSet ,这是一个可以更改的单独集合的视图,此类的实例包含自己的私有数据,永远不会更改。这个类对于公共静态最终集(常量集)很方便,也可以让你轻松地为调用者提供给你的类的集合的防御性副本。

Unlike Collections.unmodifiableSet, which is a view of a separate collection that can still change, an instance of this class contains its own private data and will never change. This class is convenient for public static final sets ("constant sets") and also lets you easily make a "defensive copy" of a set provided to your class by a caller.

但是 ImmutableSet 仍然存储元素的引用,我无法找出与 Collections.unmodifiableSet()。示例:

But the ImmutableSet still stores reference of elements, I couldn't figure out the difference to Collections.unmodifiableSet(). Sample:

StringBuffer s=new StringBuffer("a");
ImmutableSet<StringBuffer> set= ImmutableSet.of(s);
s.append("b");//s is "ab", s is still changed here!

有人可以解释一下吗?

推荐答案

考虑一下:

Set<String> x = new HashSet<String>();
x.add("foo");

ImmutableSet<String> guava = ImmutableSet.copyOf(x);
Set<String> builtIn = Collections.unmodifiableSet(x);

x.add("bar");
System.out.println(guava.size()); // Prints 1
System.out.println(builtIn.size()); // Prints 2

换句话说, ImmutableSet 尽管它有可能通过改变而构建的任何集合,但它是不可变的 - 因为它创建了一个副本。 Collections.unmodifiableSet 可以防止返回的集合被直接更改,但它仍然是可能更改的后备集的视图。

In other words, ImmutableSet is immutable despite whatever collection it's built from potentially changing - because it creates a copy. Collections.unmodifiableSet prevents the returned collection from being directly changed, but it's still a view on a potentially-changing backing set.

请注意,如果您开始通过任何一组更改引用对象的内容,则无论如何都会关闭所有投注。不要那样做。实际上,首先使用可变元素类型创建集合并不是一个好主意。 (使用可变密钥类型进行Ditto映射。)

Note that if you start changing the contents of the objects referred to by any set, all bets are off anyway. Don't do that. Indeed, it's rarely a good idea to create a set using a mutable element type in the first place. (Ditto maps using a mutable key type.)

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

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