📜  Java Collections emptyList() 方法和示例

📅  最后修改于: 2022-05-13 01:54:37.552000             🧑  作者: Mango

Java Collections emptyList() 方法和示例

Java Collections 的emptyList()方法返回没有元素的列表。这种方法是不可变的。也就是说,我们在创建这个方法后不能做任何修改。

句法:

public static final  List emptyList()  

参数:它不会接受任何参数

返回:此方法将返回一个空列表

示例 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 mylist
            = Collections.emptyList();
             
        // display the list
        System.out.println(mylist);
    }
}


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 mylist
            = Collections.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);
    }
}


输出
[]

示例 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 mylist
            = Collections.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);
    }
}

输出:

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)