ImmutableSet.of()的用法示例

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值