Menu
Topics Index
...
`


Collections Framework > Collection Algorithms >
Siva Nookala - 14 Apr 2016
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>();
oneStringList.add("Gowthami");
oneStringList = Collections.unmodifiableList(oneStringList);
we could do
List<String> oneStringList = Collections.singletonList("Gowthami");
Singleton Collections Demo
import java.util.*;

class SingletonCollectionsDemo
{
    public static void main(String arg[])
    {
        /* WHEN YOU WANT A LIST WITH ONLY ONE ELEMENT USE singletonList */
        List<String> oneStringList = Collections.singletonList("Gowthami");
        
        System.out.println("Created Singleton List : " + oneStringList);
        
        // CAN NOT MODIFY A SINGLETON LIST. IT THROWS EXCEPTION
        // oneStringList.add("Saranya"); // LINE A    
    }
}
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
  • Uncomment LINE A and see how the UnsupportedOperationException is thrown.
  • Create a singleton Set or singleton Map using singleton and singletonMap respectively. Also try modifying them and see how it throws an exception.

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.