Java中Collections.singletonList的使用
在Java中,Collections.singletonList 是一个用于创建包含单个元素的不可变列表(Immutable List)的实用方法。这个方法返回一个只包含指定对象的列表,该列表是不可修改的,即不能添加、删除或修改其中的元素。以下是使用 Collections.singletonList 的基本语法:
- import java.util.Collections;
- import java.util.List;
-
- public class SingletonListExample {
- public static void main(String[] args) {
- // 创建一个只包含单个元素的不可变列表
- String singleElement = "Hello";
- List<String> singletonList = Collections.singletonList(singleElement);
-
- // 输出列表内容
- System.out.println("Singleton List: " + singletonList);
-
- // 尝试修改列表会抛出 UnsupportedOperationException
- // singletonList.add("World"); // 会抛出 UnsupportedOperationException
- }
- }
输出结果:
Singleton List: [Hello]
在上面的例子中,singletonList 包含了一个字符串元素 "Hello"。请注意,由于该列表是不可修改的,任何尝试添加、删除或修改元素的操作都会导致 UnsupportedOperationException。Collections.singletonList 的主要用途是在需要传递一个列表但只有一个元素的情况下,提供一个方便的方式来创建不可变的列表。这可以在某些API或方法签名中很有用,因为它明确表示只有一个元素,并且不允许修改。