Java Map convert to read only map

Description

Java Map convert to read only map

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class Main {
  public static void main(String[] argv) throws Exception {

    Map<String,String> map = new HashMap<>();
    map.put("CSS", "style");
    /*from w  ww . j  ava 2s.  c  om*/
    System.out.println(map);
    
    map = Collections.unmodifiableMap(map);

    try {
      map.put("key", "new value");
    } catch (UnsupportedOperationException e) {
      System.out.println("cannot change");
    }

  }
}



PreviousNext

Related