CODE
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
}
}
Created Singleton List : [Gowthami]
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.
LINE A
and see how the UnsupportedOperationException
is thrown.Set
or singleton Map
using singleton
and singletonMap
respectively. Also try modifying them and see how it throws an exception.