使用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 args参数。
这些方法返回不可变的映射,并且无法添加,删除或替换元素。调用任何mutator方法都将始终引发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)