Java Utility Library

Java Collections - emptySet() Method



The java.util.Collections.emptySet() method returns an empty set (immutable). This set is serializable.

Syntax

public static final <T> List<T> emptySet()

Here, T is the type of element, if there were any, in the set.


Parameters

No parameter is required.

Return Value

Returns an empty immutable set.

Exception

NA.

Example:

In the example below, the java.util.Collections.emptySet() method is used to create an empty immutable set.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating an empty set
    Set<Integer> MySet = Collections.emptySet();

    //print the content of the set
    System.out.println("MySet contains: " + MySet);

    //populating the set
    //as the set is immutable, 
    //the exception is thrown 
    MySet.add(10);
    MySet.add(20);
    MySet.add(30);
    MySet.add(40);
    MySet.add(50);

    //print the content of the set
    System.out.println("MySet contains: " + MySet);
  }
}

The output of the above code will be:

MySet contains: []

Exception in thread "main" java.lang.UnsupportedOperationException
    at java.base/java.util.AbstractCollection.add(AbstractCollection.java:267)
    at MyClass.main(MyClass.java:14)

❮ Java.util - Collections