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.
Compare these methods with Collections.unmodifiableXXX() methods. The umodifiableXXX methods already accept a collection as an argument.
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.
Compare these methods with Collections.unmodifiableXXX() methods. The umodifiableXXX methods already accept a collection as an argument.
Comments