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
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:
Example 1: Applying the “emptyList()” Method in Java
This example applies the “emptyList()” method to define a list comprising no any elements:
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 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.