Make a Hashtable read-only in Java

Java 8Object Oriented ProgrammingProgramming

Read-only Hashtable would mean users won’t be able to add or remove elements from it. Let us first create a Hashtable with key-value pair −

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");

Now, use unmodifiableMap() to form a Hashtable read-only −

Map<String, String>m = Collections.unmodifiableMap(hash);

Example

 Live Demo

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!");
   }
}

Output

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!
raja
Published on 25-Apr-2019 09:41:18
Advertisements