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

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

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

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

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

    For example:

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

    All of these fail at runtime. In contrast:

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

    This is fine.

提交回复
热议问题