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

问题描述

ImmutableSet 的JavaDoc说:

JavaDoc of ImmutableSet says:

但是 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有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 01:20