ImmutableList.of()
是 Google Guava 库 提供的一个静态工厂方法,用于创建一个不可变的(immutable)列表。
✅ 简单理解:
java
编辑
List<String> list = ImmutableList.of("A", "B", "C");
这行代码会创建一个包含 "A"
、"B"
、"C"
的 不可变列表。
🔍 详细解释
1. ImmutableList
是什么?
- 来自 Google Guava 库(
com.google.common.collect.ImmutableList
) - 是一个 不可变集合(Immutable Collection)
- 一旦创建,就不能再添加、删除、修改元素
类似于 Java 自带的
Collections.unmodifiableList(...)
,但更安全、更高效、API 更友好。
2. of()
方法的作用
ImmutableList.of(...)
是一组重载的静态方法,用于创建小规模的不可变列表。
常见用法:
java
编辑
// 创建空列表
ImmutableList<String> empty = ImmutableList.of();
// 创建单个元素
ImmutableList<String> one = ImmutableList.of("A");
// 创建多个元素(最多 5 个,Guava 提供了重载)
ImmutableList<String> three = ImmutableList.of("A", "B", "C");
// 创建更多元素(使用 varargs)
ImmutableList<Integer> many = ImmutableList.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
⚠️ 注意:
of()
方法最多支持 5 个参数的重载,超过 5 个会使用varargs
版本。
3. 不可变(Immutable)意味着什么?
一旦创建,就不能:
java
编辑
list.add("X"); // ❌ 抛出 UnsupportedOperationException
list.remove(0); // ❌ 抛出 UnsupportedOperationException
list.set(0, "X"); // ❌ 抛出 UnsupportedOperationException
4. 为什么使用 ImmutableList.of()
?
优点 | 说明 |
---|---|
✅ 线程安全 | 不可变,天然线程安全,无需同步 |
✅ 防止意外修改 | 避免被其他代码修改,提高健壮性 |
✅ 性能好 | 小列表有优化实现,比 new ArrayList<>() + add() 更快 |
✅ 可作为常量 | 适合定义常量列表 |
✅ 函数式编程友好 | 与 Stream、Optional 等配合良好 |
5. 实际例子
java
编辑
public class Constants {
// 定义一个不可变的允许类型列表
public static final ImmutableList<String> ALLOWED_TYPES =
ImmutableList.of("PDF", "DOCX", "XLSX", "PPTX");
}
外部代码无法修改这个列表,保证了安全性。
6. 和 Java 自带方法对比
方式 | 是否不可变 | 是否高效 | 是否可读 |
---|---|---|---|
Arrays.asList("A", "B") |
❌ 可通过 set() 修改元素 |
✅ | ✅ |
Collections.unmodifiableList(list) |
✅ | ❌ 需要先创建 list | ❌ |
List.of("A", "B") (Java 9+) |
✅ | ✅ | ✅ |
ImmutableList.of("A", "B") (Guava) |
✅ | ✅ | ✅ |
⚠️ 从 Java 9 开始,JDK 原生提供了
List.of()
,功能类似ImmutableList.of()
,但 Guava 的ImmutableList
功能更丰富(如copyOf
,builder()
等)。
✅ 总结
表达式 | 含义 |
---|---|
ImmutableList.of("A", "B") |
创建一个不可变列表,包含 A 和 B |
不可变 | 不能增删改 |
适合 | 常量、配置、函数返回值、防止副作用 |
📦 依赖说明(Maven)
xml
编辑
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>32.1.3-jre</version>
</dependency>
✅ 所以你看到的:
java
编辑
ImmutableList<SessionChatRecordEntity> list
表示:一个不可变的 SessionChatRecordEntity
列表,通常用于传递一组不会被修改的数据。