让我们首先创建一个Hashtable并设置键值对-
Hashtable<String,String>hash = new Hashtable<String,String>(); hash.put("key1", "value1"); hash.put("key2", "value2"); hash.put("key3", "value3");
现在,创建一个不可修改的映射-
Map map = Collections.unmodifiableMap(hash);
如果您尝试向映射添加新的键和值,则会产生错误-
Exception in thread "main" java.lang.UnsupportedOperationException
import java.util.*; public class Demo { public static void main(String[] s) { Hashtable<String,String>hash = new Hashtable<String,String>(); hash.put("key1", "value1"); hash.put("key2", "value2"); hash.put("key3", "value3"); System.out.println("Initial collection: "+hash); Map map = Collections.unmodifiableMap(hash); //错误将生成 map.put("key3", "value3"); } }
它将显示输出,但有一个例外-
输出结果
Initial collection: {key3=value3, key2=value2, key1=value1} Exception in thread "main" java.lang.UnsupportedOperationException