Creating a Collection with a single element

Question: What is the most efficient way of creating a collection (Set, List or Map) with a single element?

Answer: The most efficient way of creating a collection with a single element would be to make use of the Collections.singletonXXX() methods.
  • Collections.singleton - To create a set that has only one element.
  • Collections.singletonList - To create a list that has only one element.
  • Collections.singletonMap - To crate a map that has only one entry.
The collections returned from these methods are immutable.

Compare these methods with Collections.unmodifiableXXX() methods. The umodifiableXXX methods already accept a collection as an argument.

Comments

ur3cma said…
Useful info, thanks.

Popular posts from this blog

Gotchas with DBCP

A note on Java's Calendar set() method

The mysterious ORA-03111 error