The methods
singleton , singletonList and singletonMap are convenience methods for creating the collections with only one elements. The objects hence created are immutable (unmodifiable). These methods save the pain of creating the Collection, adding the element and making them as unmodifiable.
Instead of doing
List<String> oneStringList = new ArrayList<String>(); List<String> oneStringList = Collections.singletonList("Gowthami"); Singleton Collections Demo CODE import java.util.*; OUTPUT Created Singleton List : [Gowthami] DESCRIPTION Here, we created a List containing only one element. This is a convenient way than creating a list first, adding an element and then making it as unmodifiable. Note the lists created like this are immutable, which means making any changes to the list like add, remove or set will throw an Exception. THINGS TO TRY
|