Java

What is Java Collections emptyList() Method

While programming in Java, there can be numerous scenarios where the developer needs to allocate data or a part of it as confidential or utilize it in the future. In such situations, the Java collections “emptyList()” method is of great aid in allocating a memory space or a template for appending some specific records.

This blog will elaborate on applying the “emptyList()” method in Java.

What is Java Collections “emptyList()” Method?

The “emptyList()” method in Java is utilized to return a list that has no elements. These empty lists are immutable in nature. It is such that one cannot apply any modifications i.e., “adding elements to the list” etc. after applying this method. Also, this list is serializable.

Syntax

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

This method gives an empty list in return.

Before heading to the examples, import the following package to invoke all the classes within the “java.util” package:

import java.util.*;

Example 1: Applying the “emptyList()” Method in Java
This example applies the “emptyList()” method to define a list comprising no any elements:

public class Emptylist {
 public static void main(String[] args) {
  List<String> list = Collections.<String>emptyList();
  System.out.println("Empty list -> "+list);
}}

In the above code snippet, create an empty list of “String” data types and get it.

Output

In this outcome, it can be indicated that the created empty list is returned appropriately.

Example 2: Adding the Elements to the Empty List in Java
In this particular example, the elements are added to an empty list, and the corresponding outcome is analyzed upon doing so:

public class Emptylist {
 public static void main(String[] args) {
  List<Object> list = Collections.<Object>emptyList();
  list.add("Harry");
  list.add("David");
  list.add(3);
  System.out.println("The Empty List becomes -> "+list);
}}

According to the above code lines, perform the below-stated steps:

  • Likewise, create an empty list.
  • Note: Here, a list of “Object” types is defined instead to comprise both the “Integer” and “String” type values.
  • After that, associate the “add()” method with the list to append the stated string and integer values to the list, respectively.

Output

As analyzed, modifying the method i.e., “adding elements to the list” resulted in the “UnsupportedOperationException” since the list is allocated as empty.

Conclusion

The “emptyList()” method in Java is used to get a list comprising no elements. Also, modifying this method leads to the “UnsupportedOperationException” since the list is empty. This blog discussed the usage and implementation of the “emptyList()” method in Java.

About the author

Umar Hassan

I am a Front-End Web Developer. Being a technical author, I try to learn new things and adapt with them every day. I am passionate to write about evolving software tools and technologies and make it understandable for the end-user.