[ACCEPTED]-What's the difference between Collections.unmodifiableSet() and ImmutableSet of Guava?-guava

Accepted answer
Score: 90

Consider this:

Set<String> x = new HashSet<String>();

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

System.out.println(guava.size()); // Prints 1
System.out.println(builtIn.size()); // Prints 2

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

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

Score: 21

Besides the behavioral difference that Jon 9 mentions, an important difference between 8 ImmutableSet and the Set created by Collections.unmodifiableSet is that ImmutableSet is a type. You 7 can pass one around and have it remain clear 6 that the set is immutable by using ImmutableSet rather 5 than Set throughout the code. With Collections.unmodifiableSet, the returned 4 type is just Set... so it's only clear that 3 the set is unmodifiable at the point where 2 it is created unless you add Javadoc everywhere 1 you pass that Set saying "this set is unmodifiable".

Score: 10

Kevin Bourrillion (Guava lead developer) compares 9 immutable / unmodifiable collections in 8 this presentation. While the presentation is two years old, and 7 focuses on "Google Collections" (which 6 is now a subpart of Guava), this is a very interesting presentation. The 5 API may have changed here and there (the 4 Google Collections API was in Beta at the 3 time), but the concepts behind Google Collections 2 / Guava are still valid.

You might also be 1 interested in this other SO question ( What is the difference between google's ImmutableList and Collections.unmodifiableList() ).

Score: 4

A difference between the two not stated 7 in other answers is that ImmutableSet does not permit 6 null values, as described in the Javadoc

A high-performance, immutable Set with 5 reliable, user-specified iteration order. Does 4 not permit null elements.

(The same restriction 3 applies to values in all Guava immutable 2 collections.)

For example:

ImmutableSet.builder().add("Hi").add(null); // Fails in the Builder.
ImmutableSet.copyOf(Arrays.asList("Hi", null));

All of these fail 1 at runtime. In contrast:

Collections.unmodifiableSet(new HashSet<>(Arrays.asList("Hi", null)));

This is fine.

More Related questions