📜  Java中的集合 singletonList() 方法及示例

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

Java中的集合 singletonList() 方法及示例

Java.util.Collections类的singletonList()方法用于返回一个只包含指定对象的不可变列表。返回的列表是可序列化的。该列表将始终仅包含一个元素,因此称为单例列表。当我们尝试在返回的单例列表中添加/删除元素时,它会给出 UnsupportedOperationException。

句法:

public static  List singletonList(T o)

参数:

This method takes the object o as a parameter to be stored in the returned list.

返回值:

This method returns an immutable list containing only the specified object.

以下是说明singletonList()方法的示例

示例 1:

Java
// Java program to demonstrate
// singletonList() method
// for  Value
 
import java.util.*;
 
public class GFG1 {
    public static void main(String[] argv)
        throws Exception
    {
 
        try {
 
            // create singleton list
            // using method singletonList() method
            List list = Collections.singletonList("E");
 
            // print the list
            System.out.println("singletonList : " + list);
        }
 
        catch (IllegalArgumentException e) {
            System.out.println("Exception thrown : " + e);
        }
    }
}


Java
// Java program to demonstrate
// singletonList() method
// for  Value
 
import java.util.*;
 
public class GFG1 {
    public static void main(String[] argv)
        throws Exception
    {
 
        try {
 
            // create singleton list
            // using method singletonList() method
            List list = Collections.singletonList(20);
 
            // print the list
            System.out.println("singletonList : " + list);
        }
 
        catch (IllegalArgumentException e) {
            System.out.println("Exception thrown : " + e);
        }
    }
}


输出
singletonList : [E]

示例 2:

Java

// Java program to demonstrate
// singletonList() method
// for  Value
 
import java.util.*;
 
public class GFG1 {
    public static void main(String[] argv)
        throws Exception
    {
 
        try {
 
            // create singleton list
            // using method singletonList() method
            List list = Collections.singletonList(20);
 
            // print the list
            System.out.println("singletonList : " + list);
        }
 
        catch (IllegalArgumentException e) {
            System.out.println("Exception thrown : " + e);
        }
    }
}
输出
singletonList : [20]