Java Collection How to - Create final HashMap that should not allow to update or remove element








Question

We would like to know how to create final HashMap that should not allow to update or remove element.

Answer

import java.util.Collections;
import java.util.Hashtable;
import java.util.Map;
// ww  w.  j a  v a2s  . c  om
public class Main {
  public static void main(String[] s) {
    Hashtable<String, String> table = new Hashtable<String, String>();

    table.put("1", "Sunday");
    table.put("2", "Monday");
    table.put("3", "Tuesday");
    table.put("4", "Wednesday");
    table.put("5", "Thursday");
    table.put("6", "Friday");
    table.put("7", "Saturday");

    System.out.println("Initial collection: " + table);

    Map m = Collections.unmodifiableMap(table);

    // m.put("key3", "value3");
  }
}

The code above generates the following result.