真正的人生,只有在经过艰难卓绝的斗争之后才能实现。——塞涅卡
在java8
中
我们可以使用下面的函数创建只读集合
Collections.unmodifiableCollection(Arrays.asList(""));
Collections.unmodifiableList(Collections.singletonList(""));
Collections.unmodifiableMap(new HashMap<>(1 << 4));
Collections.unmodifiableSet(new HashSet<>());
Collections.unmodifiableNavigableMap(new TreeMap<>());
Collections.unmodifiableNavigableSet(new TreeSet<>());
Collections.unmodifiableSortedMap(new TreeMap<>());
Collections.unmodifiableSortedSet(new TreeSet<>());
到了java9
我们可以使用如下的新函数创建只读集合
List<Integer> list = List.of(1, 2, 3, 4, 5, 6);
Set<Integer> sets = Set.of(1, 2, 3, 4, 5, 6);
Map<Integer, Integer> maps = Map.of(1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6);
Map<Integer, Integer> entries = Map.ofEntries(Map.entry(1, 1),
Map.entry(2, 2),
Map.entry(3, 3),
Map.entry(4, 4),
Map.entry(5, 5),
Map.entry(6, 6));
还是很方便的