Search code examples
javasetsingletonjava-9

Set.of vs Collections.singleton


Since the immutable implementation of Set.of(E e) has been introduced in Java 9, do we still need to use Collections.singleton(E e)? What would be the use case for the latter one?

It doesn't seem to be obvious from looking at the source code of both implementations. I don't see any significant difference except that Set12 implementation explicitly denies deserialisation.

I would personally go for Set.of(...) for the all new code at least because of the stylish point of view (a shorter code, less imports). But may be I am missing some crucial point?


Solution

  • The two methods behave almost the same. The only difference I can think of is that Collections.singleton() allows a null element, while Set.of() does not.

    This will work:

    Set<String> setofnull = Collections.singleton(null);
    

    This won't (it will throw NullPointerException):

    Set<String> setofnull = Set.of(null);
    

    If the element you are putting in the Set cannot be null, I'd go with Set.of() too.