java9之前我们给集合创建实例的方法如下:
Set<String> set = new HashSet<>();
set.add("A");
set.add("B");
set.add("C");
System.out.println(set);
List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
System.out.println(list);
Map<String, String> map = new HashMap<>();
map.put("A","Apple");
map.put("B","Boy");
map.put("C","Cat");
System.out.println(map);
结果如下:
[A, B, C]
[A, B, C]
{A=Apple, B=Boy, C=Cat}
Java9之后我们可以这样创建实例
Set<String> set = Set.of("A", "B", "C");
System.out.println(set);
List<String> list = List.of("A", "B", "C");
System.out.println(list);
Map<String, String> map = Map.of("A", "Apple", "B", "Boy", "C", "Cat");
System.out.println(map);
Map<String, String> map1 = Map.ofEntries(
new AbstractMap.SimpleEntry<>("A", "Apple"),
new AbstractMap.SimpleEntry<>("B", "Boy"),
new AbstractMap.SimpleEntry<>("C", "Cat"));
System.out.println(map1);
结果如下:
[A, C, B]
[A, B, C]
{A=Apple, C=Cat, B=Boy}
{A=Apple, C=Cat, B=Boy}
可以看出代码简化了不少,总结如下:
static <E> List<E> of(E e1, E e2, E e3);
static <E> Set<E> of(E e1, E e2, E e3);
static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2, K k3, V v3);
static <K,V> Map<K,V> ofEntries(Map.Entry<? extends K,? extends V>... entries)
但是需要注意的是
List与Set的of方法重载了0~10个参数的不同方法和一个以(E... element)作为参数列表的方法
Map的of方法重载了0~10对(键值为一对,所以也是0~20个参数(偶数))参数的不同方法
如果超过10对参数,Map需要使用ofEntries方法