Java SE 9 中用於建立不可變的 Map 的工廠方法


隨著 Java 9 的釋出,新的工廠方法被新增到 Map 介面,用於建立不可變的例項。這些工廠方法是便捷工廠方法,可以以更簡潔、更簡明的方式建立集合。

建立集合的舊方法

示例

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class Tester {
   public static void main(String []args) {

      Map<String, String> map = new HashMap<>();

      map.put("A","Apple");
      map.put("B","Boy");
      map.put("C","Cat");
      Map<String, String> readOnlyMap = Collections.unmodifiableMap(map);
      System.out.println(readOnlyMap);
      try {
         readOnlyMap.remove(0);
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

輸出

它將列印以下輸出。

{A = Apple, B = Boy, C = Cat}
java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableMap.remove(Collections.java:1460)
at Tester.main(Tester.java:15)

新方法

使用 Java 9,以下方法連同它們的過載對應項被新增到 Map 介面中。

static <E> Map<E> of(); // returns immutable set of zero element
static <E> Map<E> of(K k, V v); // returns immutable set of one element
static <E> Map<E> of(K k1, V v1, K k2, V v2); // returns immutable set of two elements
static <E> Map<E> 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)// Returns an immutable map containing keys and values extracted from the given entries.

注意事項

  • 對於 Map 介面,of(...) 方法被過載為具有 0 到 10 個引數,而 ofEntries 具有 var 引數。

  • 這些方法返回不可變的 map,且不能新增、刪除或替換元素。呼叫任何變更器方法始終會導致丟擲 UnsupportedOperationException。

建立不可變集合的新方法

示例

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class Tester {
   public static void main(String []args) {

      Map<String, String> map = Map.of("A","Apple","B","Boy","C","Cat");
      System.out.println(map);
      try {
         map.remove(0);
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

輸出

它將列印以下輸出。

{A = Apple, B = Boy, C = Cat}
java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableMap.remove(Collections.java:1460)
at Tester.main(Tester.java:15)

更新於:21-Jun-2020

167 次瀏覽

開啟你的職業

完成課程,獲得認證

開始
廣告
© . All rights reserved.