天天看點

java9-快速建立不可變集合

在java9中對,List,Set,Map提供了快速建立不可變集合的方法.

  • ​List.of(....)​

@Test
    public void test1(){
        List<Object> list1 = List.of(12,34,543,765);
        //list1.add(1);
        System.out.println(list1);
    }      

若執行添加操作,會抛出​

​UnsupportedOperationException​

​異常

  • ​Set.of(...)​

@Test
    public void test1() {
        Set<Object> set1 = Set.of(12, 34, 543, 765);
        //set1.add(1);
        System.out.println(set1);
    }      
  • ​Map.of(...)​

    ​​或者​

    ​Map.ofEntries(entry...)​

/**
     * Map.of(...)建立任意參數的不可變集合
     */
    @Test
    public void test1() {
        Map<String, ? extends Serializable> map1 = Map.of("name", "小紅", "age", 24);
        System.out.println(map1);
    }

    /**
     * 可以用Map.entry包裝鍵值對
     */
    @Test
    public void test2() {
        Map<String, String> map2 =
                Map.ofEntries(entry("name", "小紅"),
                        entry("age", "24"));
        map2.forEach((k, v) ->
                System.out.printf("key = %s, value = %s  ", k, v));
    }