ImmutableMap.
时间: 2023-09-19 09:11:46 浏览: 45
ImmutableMap是Google Guava库中的一个不可变的Map实现,它的特点是在创建后不能被修改,也就是说其中的键值对都是不可变的。ImmutableMap实现了Map接口,提供了与标准Map相同的功能,包括获取、遍历、查询、删除等操作。ImmutableMap的创建方式有多种,包括如下几种:
1. 使用of()方法创建:
```java
ImmutableMap<String, Integer> map = ImmutableMap.of("a", 1, "b", 2, "c", 3);
```
2. 使用Builder创建:
```java
ImmutableMap<String, Integer> map = new ImmutableMap.Builder<String, Integer>()
.put("a", 1)
.put("b", 2)
.put("c", 3)
.build();
```
3. 使用copyOf方法创建:
```java
Map<String, Integer> tempMap = new HashMap<>();
tempMap.put("a", 1);
tempMap.put("b", 2);
tempMap.put("c", 3);
ImmutableMap<String, Integer> map = ImmutableMap.copyOf(tempMap);
```
ImmutableMap的不可变性使得它在多线程环境下非常安全,因为它不需要加锁来保证线程安全。同时,由于不可变性,ImmutableMap也可以作为常量来使用,防止在程序运行中被修改。