Java Collections unmodifiableMap() Method
Example
Try to add an item to a read-only map:
import java.util.HashMap;
import java.util.Collections;
import java.util.Map;
public class Main {
public static void main(String[] args) {
HashMap<String, String> capitalCities = new HashMap<String, String>();
capitalCities.put("England", "London");
Map<String, String> readOnly = Collections.unmodifiableMap(capitalCities);
try {
readOnly.put("Germany", "Berlin");
} catch (UnsupportedOperationException e) {
System.out.println("Error: the map cannot be changed.");
}
}
}
Definition and Usage
The unmodifiableMap() method returns an unmodifiable (read-only) view of a map. You can read the keys and values, but you cannot add, remove or change them. If you try, Java throws an UnsupportedOperationException.
The view is not a copy. If the original map changes, the view shows the change.
Syntax
public static Map<K,V> unmodifiableMap(Map<K,V> map)
K and V refer to the data types of the keys and values of the map.
Parameter Values
| Parameter | Description |
|---|---|
| map | Required. The map to make a read-only view of. |
Technical Details
| Returns: | A read-only Map that shows the keys and values of the original map. |
|---|
Related Pages
Java Collections Framework Tutorial
❮ Collections Methods