创建不可变集合的三个方法
- static <E>List<E> of(E...elements]
- static <E>Set<E> of(E...elements)
- static <k ,w> Map<k, V> of(E...elements)
使用方法以及解释:
List<Object> of = List.of("a","b","c","d");
//可以实现集合的批量添加
ArrayList<String> list = new ArrayList<>(List.of("a","b","c","d"));
System.out.println(list);
list.add("e");
System.out.println(list);
//Set.of方法不能添加重复数据,否则报错
//Set<String> a = Set.of("a", "b", "c", "d", "a", "b");
//System.out.println(a);
HashSet<String> strings = new HashSet<>(Set.of("a", "b", "c", "d"));
System.out.println(strings);
//Map.ofEntries可提高代码的可读性,其使用方法与Map.of一致
Map<String, String> stringStringMap = Map.of("小戴", "福建", "小傅", "福建", "张史", "上海");
System.out.println(stringStringMap);
Map<String, String> stringStringMap1 = Map.ofEntries(
Map.entry("戴", "23"),
Map.entry("李", "55"),
Map.entry("王", "34"));
System.out.println(stringStringMap1);
如代码及注释所示