Nir Nir - 3 months ago 22
Java Question

Implementation of Collections.singleton as a static factory method

On Java Tutorial about collection it is stated that:

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

Why does
need to return immutable?


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.