Wednesday, July 3, 2024
HomeLanguagesJavaJava Collections emptyList() Method with Examples

Java Collections emptyList() Method with Examples

The emptyList() method of Java Collections returns the list with no elements. This method is immutable. That is, we can not do any modifications after creating this method.

Syntax:

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

Parameters: It will not accept any parameters

Return: This method will return an empty list

Example 1: 

Java




// Java program to create an empty list
import java.util.*;
 
public class GFG {
 
    public static void main(String[] args)
    {
        // create a list that is empty
        List<String> mylist
            = Collections.<String>emptyList();
             
        // display the list
        System.out.println(mylist);
    }
}


Output

[]

Example 2:

Java




// Java program to show an exception
// when adding the elements to the list
import java.util.*;
 
public class GFG {
 
    public static void main(String[] args)
    {
        // create a list that is empty
        List<Integer> mylist
            = Collections.<Integer>emptyList();
 
        // add 5 elements to the created list
        mylist.add(1);
        mylist.add(2);
        mylist.add(3);
        mylist.add(4);
        mylist.add(5);
 
        // display the list
        System.out.println(mylist);
    }
}


Output:

Exception in thread "main" java.lang.UnsupportedOperationException
    at java.util.AbstractList.add(AbstractList.java:148)
    at java.util.AbstractList.add(AbstractList.java:108)
    at GFG.main(GFG.java:11)

Nokonwaba Nkukhwana
Experience as a skilled Java developer and proven expertise in using tools and technical developments to drive improvements throughout a entire software development life cycle. I have extensive industry and full life cycle experience in a java based environment, along with exceptional analytical, design and problem solving capabilities combined with excellent communication skills and ability to work alongside teams to define and refine new functionality. Currently working in springboot projects(microservices). Considering the fact that change is good, I am always keen to new challenges and growth to sharpen my skills.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments