The unmodifiableNavigableMap() method in Java is a utility method provided by the java.util.Collections class. It returns an unmodifiable view of the specified navigable 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 navigable map, ensuring that the original map remains unchanged.
Table of Contents
- Introduction
unmodifiableNavigableMap()Method Syntax- Examples
- Basic Usage of
unmodifiableNavigableMap() - Using
unmodifiableNavigableMap()with Custom Classes
- Basic Usage of
- Real-World Use Case
- Conclusion
Introduction
The Collections.unmodifiableNavigableMap() method allows you to create a read-only view of an existing navigable 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 navigable map with other parts of your program without allowing them to alter it, ensuring data integrity and immutability.
unmodifiableNavigableMap() Method Syntax
The syntax for the unmodifiableNavigableMap() method is as follows:
public static <K, V> NavigableMap<K, V> unmodifiableNavigableMap(NavigableMap<K, ? extends V> m)
Parameters:
m: The navigable map for which an unmodifiable view is to be returned.
Returns:
- An unmodifiable view of the specified navigable map.
Throws:
NullPointerExceptionif the specified navigable map is null.
Examples
Basic Usage of unmodifiableNavigableMap()
The following example demonstrates how to use the unmodifiableNavigableMap() method to create a read-only view of a navigable map.
Example
import java.util.Collections;
import java.util.NavigableMap;
import java.util.TreeMap;
public class UnmodifiableNavigableMapExample {
public static void main(String[] args) {
// Create a navigable map with initial entries
NavigableMap<String, String> navigableMap = new TreeMap<>();
navigableMap.put("Apple", "Fruit");
navigableMap.put("Carrot", "Vegetable");
navigableMap.put("Banana", "Fruit");
// Create an unmodifiable view of the navigable map
NavigableMap<String, String> unmodifiableNavigableMap = Collections.unmodifiableNavigableMap(navigableMap);
// Display the unmodifiable navigable map
System.out.println("Unmodifiable Navigable Map: " + unmodifiableNavigableMap);
// Attempt to modify the unmodifiable navigable map (will throw UnsupportedOperationException)
try {
unmodifiableNavigableMap.put("Date", "Fruit");
} catch (UnsupportedOperationException e) {
System.out.println("Error: Cannot modify an unmodifiable navigable map");
}
// Display the original navigable map after attempted modification
System.out.println("Original Navigable Map: " + navigableMap);
}
}
Output:
Unmodifiable Navigable Map: {Apple=Fruit, Banana=Fruit, Carrot=Vegetable}
Error: Cannot modify an unmodifiable navigable map
Original Navigable Map: {Apple=Fruit, Banana=Fruit, Carrot=Vegetable}
Using unmodifiableNavigableMap() with Custom Classes
You can also use the unmodifiableNavigableMap() method with maps containing instances of custom classes.
Example
import java.util.Collections;
import java.util.NavigableMap;
import java.util.TreeMap;
class Student implements Comparable<Student> {
String name;
int id;
Student(String name, int id) {
this.name = name;
this.id = id;
}
@Override
public int compareTo(Student other) {
return Integer.compare(this.id, other.id);
}
@Override
public String toString() {
return name + " (ID: " + id + ")";
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Student student = (Student) obj;
return id == student.id && name.equals(student.name);
}
@Override
public int hashCode() {
return name.hashCode();
}
}
public class CustomUnmodifiableNavigableMapExample {
public static void main(String[] args) {
// Create a navigable map of students and their scores
NavigableMap<Student, Integer> studentScores = new TreeMap<>();
studentScores.put(new Student("Amit", 101), 85);
studentScores.put(new Student("Neha", 102), 90);
studentScores.put(new Student("Raj", 103), 78);
// Create an unmodifiable view of the student navigable map
NavigableMap<Student, Integer> unmodifiableStudentScores = Collections.unmodifiableNavigableMap(studentScores);
// Display the unmodifiable student navigable map
System.out.println("Unmodifiable Student Navigable Map: " + unmodifiableStudentScores);
// Attempt to modify the unmodifiable student navigable map (will throw UnsupportedOperationException)
try {
unmodifiableStudentScores.put(new Student("Vikram", 104), 88);
} catch (UnsupportedOperationException e) {
System.out.println("Error: Cannot modify an unmodifiable student navigable map");
}
// Display the original student navigable map after attempted modification
System.out.println("Original Student Navigable Map: " + studentScores);
}
}
Output:
Unmodifiable Student Navigable Map: {Amit (ID: 101)=85, Neha (ID: 102)=90, Raj (ID: 103)=78}
Error: Cannot modify an unmodifiable student navigable map
Original Student Navigable Map: {Amit (ID: 101)=85, Neha (ID: 102)=90, Raj (ID: 103)=78}
Explanation:
-
Unmodifiable View: The
unmodifiableNavigableMap()method returns a read-only view of the specified navigable 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 navigable map.
-
Custom Class: The method works with custom class instances, allowing you to create unmodifiable views of navigable maps containing user-defined objects.
Real-World Use Case
Providing Read-Only Access to a Navigable Map
In real-world applications, the unmodifiableNavigableMap() method can be used to provide read-only access to a navigable 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 navigable map of configuration settings, and you want to provide read-only access to the settings.
import java.util.Collections;
import java.util.NavigableMap;
import java.util.TreeMap;
class Configuration {
private final NavigableMap<String, String> settings;
public Configuration() {
settings = new TreeMap<>();
settings.put("timeout", "30s");
settings.put("maxConnections", "100");
settings.put("enableLogging", "true");
}
// Method to get an unmodifiable view of the configuration settings
public NavigableMap<String, String> getSettings() {
return Collections.unmodifiableNavigableMap(settings);
}
}
public class ConfigurationExample {
public static void main(String[] args) {
Configuration config = new Configuration();
// Get the unmodifiable view of configuration settings
NavigableMap<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, maxConnections=100, timeout=30s}
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 navigable map to protect the integrity of configuration data.
Conclusion
The Collections.unmodifiableNavigableMap() method is a powerful utility for creating unmodifiable (read-only) views of navigable 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 navigable maps while providing access to them, improving the robustness and maintainability of your Java applications.