在 Java 中将哈希表设为只读
只读哈希表意味着用户将无法向其中添加或移除元素。让我们首先创建一个具有键值对的哈希表 -
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() 形成只读哈希表 -
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!
广告