1

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?

3
  • 4
    It doesn't need to, it was designed to be immutable. Commented Nov 15, 2016 at 22:40
  • 2
    And as far as design decisions go, it does allow you to make an extremely optimized set if you know there's only going to be one piece of data in it (no backing array, it's just a field for the single item). Just like the implementation of emptySet can have a darn simple contains method. Commented Nov 15, 2016 at 22:52
  • 2
    If it were mutable, you'd be able to add or remove elements. That's means it's not a singleton. Commented Nov 15, 2016 at 22:53

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Your logic about the word "singleton" is simply not true. A collection is a singleton as long as it has exactly one element. It has nothing to do with uniqueness or the singleton anti-pattern, as you seem to imply.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.