Saturday, September 28, 2024
Google search engine
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)

RELATED ARTICLES

Most Popular

Recent Comments