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

后端 未结 4 1182
迷失自我
迷失自我 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:42

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

提交回复
热议问题