Java Utility Library

Java Collections - emptyList() Method



The java.util.Collections.emptyList() method returns an empty list (immutable). This list is serializable.

Syntax

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

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


Parameters

No parameter is required.

Return Value

Returns an empty immutable list.

Exception

NA.

Example:

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

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating an empty list
    List<Integer> MyList = Collections.emptyList();

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

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

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

The output of the above code will be:

MyList contains: []

Exception in thread "main" java.lang.UnsupportedOperationException
    at java.base/java.util.AbstractList.add(AbstractList.java:153)
    at java.base/java.util.AbstractList.add(AbstractList.java:111)
    at MyClass.main(MyClass.java:14)

❮ Java.util - Collections