What's the difference between Collections.unmodifiableSet() and ImmutableSet of Guava?

后端 未结 4 1178
迷失自我
迷失自我 2020-12-13 05:57

JavaDoc of ImmutableSet says:

Unlike Collections.unmodifiableSet, which is a view of a separate collection that can sti

4条回答
  •  [愿得一人]
    2020-12-13 06:54

    Consider this:

    Set x = new HashSet();
    x.add("foo");
    
    ImmutableSet guava = ImmutableSet.copyOf(x);
    Set builtIn = Collections.unmodifiableSet(x);
    
    x.add("bar");
    System.out.println(guava.size()); // Prints 1
    System.out.println(builtIn.size()); // Prints 2
    

    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.

    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.)

提交回复
热议问题