Close

Java Collections - Collections.unmodifiableMap() Examples

Java Collections Java Java API 


Class:

java.util.Collections

java.lang.Objectjava.lang.Objectjava.util.Collectionsjava.util.CollectionsLogicBig

Method:

public static <K,V> Map<K,V> unmodifiableMap(Map<? extends K,? extends V> m)

Returns an unmodifiable view of the specified Map. Attempts to modify the returned Map, whether direct or via its collection views, result in an UnsupportedOperationException.


Examples


Since the map created by this method is a view of the original map, modifying the original will reflect the changes in it:

package com.logicbig.example.collections;

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

public class UnmodifiableMapExample {

public static void main(String... args) {
Map<Integer, String> map = new HashMap<>();
map.put(1, "one");
map.put(2, "two");
System.out.println("Original Map: " + map);
Map<Integer, String> map2 = Collections.unmodifiableMap(map);
System.out.println("unmodifiableMap: " + map2);
//modifying the original
map.put(3, "three");
map.put(4, "four");
map.remove(1);
System.out.println("unmodifiableMap: " + map2);
}
}

Output

Original Map: {1=one, 2=two}
unmodifiableMap: {1=one, 2=two}
unmodifiableMap: {2=two, 3=three, 4=four}




Modifying itself will throw the exception:

package com.logicbig.example.collections;

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

public class UnmodifiableMapExample2 {

public static void main(String... args) {
Map<Integer, String> map = new HashMap<>();
map.put(1, "one");
map.put(2, "two");
Map<Integer, String> map2 = Collections.unmodifiableMap(map);
map2.put(3, "three");
}
}

Output

Caused by: java.lang.UnsupportedOperationException
at java.base/java.util.Collections$UnmodifiableMap.put(Collections.java:1453)
at com.logicbig.example.collections.UnmodifiableMapExample2.main(UnmodifiableMapExample2.java:20)
... 6 more




See Also