javacollections

What is the benefit for Collections.singleton() to return a Set instead of a Collection?


The Collections.singleton() method returns a Set with that single argument instead of a Collection.

Why is that so? From what I can see, apart from Set being a subtype of Collection, I can see no advantage... Is this only because Set extends Collection anyway so there is no reason not to?

And yes, there is also Collections.singletonList() but this is another matter since you can access random elements from a List with .get()...


Solution

  • I'm not sure there's a "benefit" or "advantage" per se? It's just the method that returns a singleton Set, and happens to be the default implementation when you want a singleton Collection as well, since a singleton Collection happens to be a mathematical set as well.