编写一个初始化之后,不可修改的集合(比如:Map、List、Set等不可变对象)

本文探讨如何使用Collections.unmodifiableXXX和Guava的ImmutableXXX方法创建初始化后不可修改的集合,包括List、Set和Map。这些不可变对象确保了数据的安全性和一致性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java中提供final关键字,对基本类型进行修饰,当第一次初始化后,该变量就不可被修改,比如:
private final int a = 123;
然而,对于Map等类型,我们只能对于其引用不能被再次初始化,而其中的值则可以变化,比如:
private static final Map<Integer, String> map = Maps.newHashMap();

static {
    map.put(1, "one");
    map.put(2, "two");
}

public static void main(String[] args) {
    map.put(1,"three");
    log.info("{}", map.get(1));
}
输出:
22:45:01.582 [main] INFO com.tim.concurrency.example.immutable.ImmutableExample - three
分析上述代码可知map的值由原来key为1,value为one,被改为value为three。因此,此map是域不安全的。
改进方法(通过Collectionsf方法):
static {
    map.put(1, "one");
    map.put(2, "two");
    map  = Collections.unmodifiableMap(map);
}

public static void main(String[] args) {
    log.info("{}", map.get(1));
}
分析:
上述map如果再被put,则会报异常,map.put(1, "three");则会报异常。
static {
    map.put(1, "one");
    map.put(2, "two");
    map  = Collections.unmodifiableMap(map);
}

public static void main(String[] args) {
    map.put(1, "three");
    log.info("{}", map.get(1));
}
上述代码会导致下面异常:
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableMap.put(Collections.java:1457)
at com.tim.concurrency.example.immutable.ImmutableExample.main(ImmutableExample.java:27)
分析:上述map是域安全,被初始化之后,不能被修改了。
补充(利用Collections和Guava提供的类可实现的不可变对象):

Collections.unmodifiableXXX:Collection、List、Set、Map...

Guava:ImmutableXXX:Collection、List、Set、Map...

   private final static ImmutableList<Integer> list = ImmutableList.of(1, 2, 3);  // 这样被初始化之后 list是不能被改变

    private final static ImmutableSet set = ImmutableSet.copyOf(list); // 这样被初始化之后set是不能被改变的

    public static void main(String[] args) {
        list.add(123);
        set.add(222);
    }
}

上述代码中的list和set不能再被改变。

注意:guava中的map的写法有点不一样如下:

private final static ImmutableMap<Integer, Integer> map = ImmutableMap.of(1,2,3,4,5, 6);

private final static ImmutableMap<Integer, Integer> map2 = ImmutableMap.<Integer, Integer>builder().put(1,2).put(3,4).put(5,6).build();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值