不可变集合
构建不可变集合的几种方式
JDK8
-
在JDK8中,需要引入第三方工具包
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>22.0</version> </dependency>
-
利用guava创建不可变集合
ImmutableList<Integer> list = ImmutableList.of(1, 2, 3, 4);
ImmutableMap<Object, Object> map = ImmutableMap.of();
ImmutableSet<Object> set = ImmutableSet.of();
- 这三者都是不可变集合,都具备copyOf方法。
创建一个不可变集合,将其转为可变集合
ImmutableList<Integer> of = ImmutableList.of(1, 2, 3, 4);
ArrayList<Integer> integers1 = new ArrayList<>(of);
integers1.add(6);
System.out.println(integers1);
将可变集合转为不可变集合
List<Integer> unmodifiableList = Collections.unmodifiableList(integers1);
unmodifiableList.add(66);
System.out.println(unmodifiableList);
JDK9以上版本
List<Integer> list = List.of(1,2,3);
JDK10以上版本
List<Integer> integerList = List.copyOf(list);