JDK9以后才有不可变集合
创建不可变集合的应用场景
- 如果某个数据不能被修改,可以把他拷贝到不可变集合。
- 当集合对象被不可信的库调用,不可变形式是安全的。
创建不可变集合的书写方式
在List、Set、Map接口中,都存在静态的of方法,可以获取一个不可变的集合

这个集合不能添加,不能删除,不能修改。
public class Demo01 { public static void main(String[] args) { List<String> list = List.of("张三", "李四"); Set<String> set = Set.of("张三", "李四"); Map<String, Integer> map = Map.of("张三", 18, "李四", 19); } }
|
由于Map.of()方法最多只能传递10个键值对,如果想存储超过10个的键值对,可以使用Map.ofEntries()方法
public class Demo02 { public static void main(String[] args) { HashMap<String, Integer> map = new HashMap<>(); map.put("张三", 18); Set<Map.Entry<String, Integer>> entries = map.entrySet(); Map.Entry[] arr = entries.toArray(new Map.Entry[0]); Map res = Map.ofEntries(arr); } }
|
JDK10如果想存储超过10个的键值对,可以用Map.copyOf()方法
public class Demo03 { public static void main(String[] args) { HashMap<String, Integer> map = new HashMap<>(); map.put("张三", 18); Map res = Map.copyOf(map); } }
|