Make Hashtable immutable and read-only in Java
For security reasons, it is sometimes necessary to change access rights to avoid a faulty modification. That's why Java has put a method that makes our Hashtable inaccessible for writing or in other words, a Hashtable that cannot be modified in read-only.To change the access rights, you just have to call the method of the Collections class java.util.Collections.unmodifiableMap(Map map).
public static < K,V> Map< K,V> unmodifiableMap(Map extends K,? extends V> m): This method returns an immutable Hashtable view that cannot be edited.
The following example shows the use of the java.util.Collections.unmodifiableMap().
import java.util.Collections;After compiling and executing the above code, this will produce the following result:
import java.util.Hashtable;
import java.util.Map;
public class Unmodifiable_Hashtable {
public static void main(String[] s) {
Hashtable hashtable = new Hashtable();
hashtable.put("1", "val1");
hashtable.put("2", "val2");
hashtable.put("3", "val3");
Map m = Collections.unmodifiableMap(hashtable);
m.put("4", "val4");
System.out.println(m);
}
}
Exception in thread "main" java.lang.UnsupportedOperationExceptionReferences:
at java.util.Collections$UnmodifiableMap.put(Unknown Source)
at HashTable.Unmodifiable_Hashtable.main(Unmodifiable_Hashtable.java:16)
java.util.Collections.unmodifiableMap() Method