Singleton List with singletonList()


What is singleton?

With singleton class, you can create only one object. If another object is tried to create, the JVM throws UnsupportedOperationException. A Singleton class contains only one element. If tried to add a second element, the add() method throws UnsupportedOperationException.

Singleton class limits the developer from instantiating more than one object. This idea is useful when only one object is enough, in a class, to coordinate all the actions of the class. A singleton class cannot be an interface. A singleton list contains only one element and a singleton HashMap includes only one key. A singleton object is immutable (cannot be modified to add one more element); avoids usage of add().

To obtain a singleton class from a general collection class, singletonList() method of Collections is used.

Following is the method signature

  • List singletonList(Object obj1): Returns an immutable list containing only one element obj1. The element obj1 cannot be removed or added with no further elements. Introduced with JDK 1.3.
Example on Singleton List with singletonList() method
import java.util.*;
public class CollectionsSingleton
{
  public static void main(String args[])
  {
    List numList = Collections.singletonList(new Integer(10)); 

    System.out.println("numList elements: " + numList);

    // numList.add(20);       // throws UnsupportedOperationException

    List stringList = Collections.singletonList("hello"); 
    System.out.println("\nstringList elements: " + stringList);

    //  stringList.add("world"); // throws UnsupportedOperationException
  }
}


Singleton List with singletonList()
Output screenshot on Singleton List with singletonList()

List numList = Collections.singletonList(new Integer(10));
List stringList = Collections.singletonList(“hello”);
// myList.add(20);
// stringList.add(“world”);

singletonList(new Integer(10)) of Collections class returns an object of singleton List, numList containing only one element 10. Adding one more element to numList, as numList.add(20), throws UnsupportedOperationException. Similarly with stringList also.

Similarly, a singleton map can be obtained and the value is printed as follows:

Map m1 = Collections.singletonMap(“birthdate”, new Date());
System.out.println(m1);

3 thoughts on “Singleton List with singletonList()”

Leave a Comment

Your email address will not be published.