在Java中将Hashtable设为只读
只读Hashtable意味着用户将无法在其中添加或删除元素。让我们首先创建具有键值对的Hashtable-
Hashtable<String, String>hash = new Hashtable<String, String>(); hash.put("1", "A"); hash.put("2", "B"); hash.put("3", "C"); hash.put("4", "D"); hash.put("5", "E"); hash.put("6", "F"); hash.put("7", "G");
现在,使用unmodifiableMap()
形成一个Hashtable只读-
Map<String, String>m = Collections.unmodifiableMap(hash);
示例
import java.util.Collections; import java.util.Hashtable; import java.util.Map; public class Demo { public static void main(String[] s) { Hashtable<String, String>hash = new Hashtable<String, String>(); hash.put("1", "A"); hash.put("2", "B"); hash.put("3", "C"); hash.put("4", "D"); hash.put("5", "E"); hash.put("6", "F"); hash.put("7", "G"); hash.put("8", "H"); hash.put("9", "I"); hash.put("10", "J"); System.out.println("Hashtable = " + hash); Map<String, String>m = Collections.unmodifiableMap(hash); System.out.println("Hashtable is now read-only!"); } }
输出结果
Hashtable = {9=I, 8=H, 7=G, 6=F, 5=E, 4=D, 3=C, 2=B, 10=J, 1=A} Hashtable is now read-only!