3

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?

Andremoniy
  • 34,031
  • 20
  • 135
  • 241
  • Quite possibly unmodifiable vs immutable as explained in [this blog](http://marxsoftware.blogspot.com/2018/01/schopenhauers-law-immutability.html). – Naman Jun 11 '19 at 06:47
  • 3
    There is a similar kind of question https://stackoverflow.com/questions/55418248/using-list-of-for-immutable-list-with-single-element-instead-of-collections-sing#comment97556151_55418248 – soorapadman Jun 11 '19 at 06:49
  • @soorapadman Indeed, closed as duplicate :p – Andremoniy Jun 11 '19 at 07:04

1 Answers1

5

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.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • 2
    in my opinion, they should deprecate `Collections.singleton()`. never is a good thing to have two methods of doing almost the same – Sharon Ben Asher Jun 11 '19 at 06:58
  • Oh, that's a nice point about having possibility to put there a null value! Though I agree with a commentator that it is not something really needed – Andremoniy Jun 11 '19 at 07:03