ImmutableSet.of()的用法示例
一、前言
ImmutableSet.of()
是 Google Guava 库中的一个静态方法,用于创建不可变的集合(Immutable Set)。它接受可变数量的参数,并返回一个包含这些元素的不可变集合。
如果您使用 Maven 构建项目,可以在 pom.xml
文件中添加以下依赖:
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>30.1-jre</version>
</dependency>
这些依赖会下载并包含 Google Guava 库,使您可以在项目中使用 ImmutableSet.of()
方法和其他 Guava 的功能。
二、代码示例
下面是 ImmutableSet.of()
方法的用法示例:
import com.google.common.collect.ImmutableSet;
public class Main {
public static void main(String[] args) {
// 创建一个包含两个元素的不可变集合
ImmutableSet<String> set1 = ImmutableSet.of("Apple", "Banana");
System.out.println(set1); // 输出: [Apple, Banana]
// 创建一个包含三个元素的不可变集合
ImmutableSet<Integer> set2 = ImmutableSet.of(1, 2, 3);
System.out.println(set2); // 输出: [1, 2, 3]
// 创建一个包含单个元素的不可变集合
ImmutableSet<Character> set3 = ImmutableSet.of('A');
System.out.println(set3); // 输出: [A]
}
}
三、总结
在上述示例中,我们使用 ImmutableSet.of()
方法创建了几个不可变集合,并打印输出它们的内容。请注意,由于不可变集合是不可更改的,因此我们不能向其添加或删除元素。如果尝试修改不可变集合,将抛出 UnsupportedOperationException
异常。
@Test
public void test02() throws Exception {
// 创建一个包含两个元素的不可变集合
ImmutableSet<String> set1 = ImmutableSet.of("Apple", "Banana");
set1.add("XiaoMi");
System.out.println(set1);
}
java.lang.UnsupportedOperationException
at com.google.common.collect.ImmutableCollection.add(ImmutableCollection.java:222)