Java Collections singletonList()方法及示例
java.util.Collections 类的 singletonList() 方法用于返回一个只包含指定对象的不可变的列表。返回的列表是可序列化的。这个列表总是只包含一个元素,因此被称为singleton list。当我们试图在返回的单子列表中添加/删除一个元素时,会产生 UnsupportedOperationException。
语法
public static List singletonList(To)
参数
该方法将对象o作为一个参数,存储在返回的列表中。
返回值
该方法返回一个只包含指定对象的不可变的列表。
以下是说明singletonList()方法的例子
例1 :
// Java program to demonstrate
// singletonList() method
// for <String> Value
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
// create singleton list
// using method singletonList() method
List<String> list = Collections.singletonList("E");
// print the list
System.out.println("singletonList : " + list);
}
catch (IllegalArgumentException e) {
System.out.println("Exception thrown : " + e);
}
}
}
输出
singletonList : [E]
例2 :
// Java program to demonstrate
// singletonList() method
// for <Integer> Value
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
// create singleton list
// using method singletonList() method
List<Integer> list = Collections.singletonList(20);
// print the list
System.out.println("singletonList : " + list);
}
catch (IllegalArgumentException e) {
System.out.println("Exception thrown : " + e);
}
}
}
输出
singletonList : [20]