The unmodifiableMap()
method in Java is a utility method provided by the java.util.Collections
class. It returns an unmodifiable view of the specified map, meaning that any attempts to modify the map through this view will result in an UnsupportedOperationException
. This method is useful when you need to provide a read-only view of a map, ensuring that the original map remains unchanged.
Table of Contents
- Introduction
unmodifiableMap()
Method Syntax- Examples
- Basic Usage of
unmodifiableMap()
- Using
unmodifiableMap()
with Custom Classes
- Basic Usage of
- Real-World Use Case
- Conclusion
Introduction
The Collections.unmodifiableMap()
method allows you to create a read-only view of an existing map. The returned map does not allow any modifications such as adding, removing, or updating entries. This is useful in scenarios where you want to share a map with other parts of your program without allowing them to alter it, ensuring data integrity and immutability.
unmodifiableMap() Method Syntax
The syntax for the unmodifiableMap()
method is as follows:
public static <K, V> Map<K, V> unmodifiableMap(Map<? extends K, ? extends V> m)
Parameters:
m
: The map for which an unmodifiable view is to be returned.
Returns:
- An unmodifiable view of the specified map.
Throws:
NullPointerException
if the specified map is null.
Examples
Basic Usage of unmodifiableMap()
The following example demonstrates how to use the unmodifiableMap()
method to create a read-only view of a map.
Example
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class UnmodifiableMapExample {
public static void main(String[] args) {
// Create a map with initial entries
Map<String, String> map = new HashMap<>();
map.put("Apple", "Fruit");
map.put("Carrot", "Vegetable");
map.put("Banana", "Fruit");
// Create an unmodifiable view of the map
Map<String, String> unmodifiableMap = Collections.unmodifiableMap(map);
// Display the unmodifiable map
System.out.println("Unmodifiable Map: " + unmodifiableMap);
// Attempt to modify the unmodifiable map (will throw UnsupportedOperationException)
try {
unmodifiableMap.put("Date", "Fruit");
} catch (UnsupportedOperationException e) {
System.out.println("Error: Cannot modify an unmodifiable map");
}
// Display the original map after attempted modification
System.out.println("Original Map: " + map);
}
}
Output:
Unmodifiable Map: {Apple=Fruit, Carrot=Vegetable, Banana=Fruit}
Error: Cannot modify an unmodifiable map
Original Map: {Apple=Fruit, Carrot=Vegetable, Banana=Fruit}
Using unmodifiableMap() with Custom Classes
You can also use the unmodifiableMap()
method with maps containing instances of custom classes.
Example
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
class Student {
String name;
Student(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Student student = (Student) obj;
return name.equals(student.name);
}
@Override
public int hashCode() {
return name.hashCode();
}
}
public class CustomUnmodifiableMapExample {
public static void main(String[] args) {
// Create a map of students and their scores
Map<Student, Integer> studentScores = new HashMap<>();
studentScores.put(new Student("Amit"), 85);
studentScores.put(new Student("Neha"), 90);
studentScores.put(new Student("Raj"), 78);
// Create an unmodifiable view of the student map
Map<Student, Integer> unmodifiableStudentScores = Collections.unmodifiableMap(studentScores);
// Display the unmodifiable student map
System.out.println("Unmodifiable Student Map: " + unmodifiableStudentScores);
// Attempt to modify the unmodifiable student map (will throw UnsupportedOperationException)
try {
unmodifiableStudentScores.put(new Student("Vikram"), 88);
} catch (UnsupportedOperationException e) {
System.out.println("Error: Cannot modify an unmodifiable student map");
}
// Display the original student map after attempted modification
System.out.println("Original Student Map: " + studentScores);
}
}
Output:
Unmodifiable Student Map: {Neha=90, Amit=85, Raj=78}
Error: Cannot modify an unmodifiable student map
Original Student Map: {Neha=90, Amit=85, Raj=78}
Explanation:
-
Unmodifiable View: The
unmodifiableMap()
method returns a read-only view of the specified map, ensuring that any attempts to modify the map through this view will result in anUnsupportedOperationException
. -
Immutable Nature: The example shows that any modification attempts result in an exception, demonstrating the immutability of the unmodifiable map.
-
Custom Class: The method works with custom class instances, allowing you to create unmodifiable views of maps containing user-defined objects.
Real-World Use Case
Providing Read-Only Access to a Map
In real-world applications, the unmodifiableMap()
method can be used to provide read-only access to a map, such as when returning a map from a method that should not be modified by the caller.
Example
Imagine a scenario where you have a class that manages a map of configuration settings, and you want to provide read-only access to the settings.
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
class Configuration {
private final Map<String, String> settings;
public Configuration() {
settings = new HashMap<>();
settings.put("timeout", "30s");
settings.put("maxConnections", "100");
settings.put("enableLogging", "true");
}
// Method to get an unmodifiable view of the configuration settings
public Map<String, String> getSettings() {
return Collections.unmodifiableMap(settings);
}
}
public class ConfigurationExample {
public static void main(String[] args) {
Configuration config = new Configuration();
// Get the unmodifiable view of configuration settings
Map<String, String> settings = config.getSettings();
// Display the configuration settings
System.out.println("Configuration Settings: " + settings);
// Attempt to modify the configuration settings (will throw UnsupportedOperationException)
try {
settings.put("newSetting", "value");
} catch (UnsupportedOperationException e) {
System.out.println("Error: Cannot modify configuration settings");
}
}
}
Output:
Configuration Settings: {enableLogging=true, timeout=30s, maxConnections=100}
Error: Cannot modify configuration settings
Explanation:
-
Read-Only Access: The
getSettings()
method returns an unmodifiable view of the configuration settings, ensuring that the settings cannot be modified externally. -
Immutable Map: The example demonstrates the use of an unmodifiable map to protect the integrity of configuration data.
Conclusion
The Collections.unmodifiableMap()
method is a powerful utility for creating unmodifiable (read-only) views of maps in Java. By providing a simple way to ensure immutability, it enhances the flexibility and safety of your code by preventing unintended modifications. This method is particularly valuable in scenarios where you need to protect the integrity of maps while providing access to them, improving the robustness and maintainability of your Java applications.