Menu
Topics Index
...
`

Singleton Collections Demo - Java Example Program


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.

© meritcampus 2019

All Rights Reserved.

Open In App