Nir Nir - 20 days ago 7
Java Question

Implementation of Collections.singleton as a static factory method

On Java Tutorial about collection it is stated that:


Collections.singleton
is a static factory method that returns an immutable Set containing only the specified element.


Why does
Collections.singleton
need to return immutable?

Answer

I think your question is 'why are the Collections.singleton methods (there are three of them for list, set and map) designed to return an immutable collection?'

In this context a singleton is simply a collection with one element. Because the collection has only one object (i.e. the singleton) it makes sense for the collection to be immutable: the client of the method should not be able to add or remove from the collection as that would be breaking the contract to store a single object.

Comments