How to create an unmodifiable map in Java?

Java 8Object Oriented ProgrammingProgramming

Let us first create a Hashtable and set key-value pair −

Hashtable<String,String>hash = new Hashtable<String,String>();
hash.put("key1", "value1");
hash.put("key2", "value2");
hash.put("key3", "value3");

Now, create an unmodifiable map −

Map map = Collections.unmodifiableMap(hash);

If you will try to add a new key and value to the Map, then error will generate −

Exception in thread "main" java.lang.UnsupportedOperationException

Example

 Live Demo

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);
      // error will generate
      map.put("key3", "value3");
   }
}

It will show output with an exception −

Output

Initial collection: {key3=value3, key2=value2, key1=value1}
Exception in thread "main" java.lang.UnsupportedOperationException
raja
Published on 24-Apr-2019 09:18:30
Advertisements