0

As far as I can see, the contracts of both are identical. Seems rather pointless to implement a whole new empty set for Set.of().

I would presume the standard library implementors are aware of Collections.emptySet(), so there must be a specific reason I am not seeing. Due to the very generic method names, searching in mailing lists is impossible, so I am not sure if this was discussed.

(BTW, it seems Set.of() just uses a SetN with an empty input array, so it will probably be less efficient than emptySet() as well.)

billc.cn
  • 7,187
  • 3
  • 39
  • 79

2 Answers2

2

Set.of() uses a nice clean helper from ImmutableCollections which was introduced with Java 9.

Collections on the other hand was says since 1.2, and was only "adapted" to generics and such things over time.

So:

  • the Collections implementation is historically grown, and you would probably not be doing it like that any more today
  • so, when introducing the functionality in a new context, you do it in a different way.

And more importantly: all the of methods within Set are just delegating to ImmutableCollections. And then it makes no sense that of() would be implemented in a completely different way than all the other of(x) methods.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
2

There is a single difference "code-wise", that I am aware of.

Collections.emptySet().contains(null); // false
Set.of().contains(null); // NullPointerException

So they are not inter-changeable.

Eugene
  • 117,005
  • 15
  • 201
  • 306
  • Also the serial form is different - if you care about interoperating through e.g. JMX with older VMs. – daniel Aug 12 '21 at 14:36