Introduction
Java 10 introduced the Map.copyOf()
method, which creates an unmodifiable copy of an existing map. This method allows you to easily create read-only maps, ensuring that the map cannot be modified after its creation. The Map.copyOf()
method is part of Java’s effort to enhance immutability and improve the safety and clarity of code.
Key Points:
- Immutable Copy:
Map.copyOf()
creates a map that cannot be changed. - Shallow Copy: The key-value pairs themselves are not deeply cloned; only references are copied.
- Null Safety:
Map.copyOf()
does not allownull
keys or values in the source map. - Read-Only: Attempting to modify the resulting map will throw an
UnsupportedOperationException
.
How to Use Map.copyOf()
To create an unmodifiable map, you can use the Map.copyOf()
method and pass an existing map to it.
Syntax:
Map<K, V> unmodifiableMap = Map.copyOf(originalMap);
- originalMap: The original map from which to create the unmodifiable copy.
- unmodifiableMap: The resulting read-only map.
Example of Using Map.copyOf()
Basic Example
Here’s a simple example demonstrating the use of Map.copyOf()
with Indian names and ages:
import java.util.*; public class MapCopyOfExample { public static void main(String[] args) { Map<String, Integer> originalMap = new HashMap<>(); originalMap.put("Rajesh", 30); originalMap.put("Priya", 25); originalMap.put("Sneha", 28); // Create an unmodifiable copy of the original map Map<String, Integer> copyMap = Map.copyOf(originalMap); System.out.println("Original Map: " + originalMap); System.out.println("Copy Map: " + copyMap); // Attempt to modify the copy try { copyMap.put("Kunal", 32); // This will throw UnsupportedOperationException } catch (UnsupportedOperationException e) { System.out.println("Cannot modify copyMap: " + e.getMessage()); } } }
Output:
Original Map: {Rajesh=30, Priya=25, Sneha=28} Copy Map: {Rajesh=30, Priya=25, Sneha=28} Cannot modify copyMap: null
Explanation:
- Immutable Copy: The
Map.copyOf()
method creates a new map that is unmodifiable, ensuring that the original map’s content cannot be altered. - UnsupportedOperationException: Any attempt to modify the resulting map will result in an
UnsupportedOperationException
.
Null Safety
The Map.copyOf()
method does not allow null
keys or values in the original map. If the original map contains null
, a NullPointerException
is thrown.
Example:
import java.util.*; public class NullSafetyExample { public static void main(String[] args) { Map<String, Integer> originalMap = new HashMap<>(); originalMap.put("Rajesh", null); originalMap.put("Priya", 25); originalMap.put("Sneha", 28); try { // Attempt to create an unmodifiable copy of a map with null values Map<String, Integer> copyMap = Map.copyOf(originalMap); } catch (NullPointerException e) { System.out.println("Map contains null values: " + e.getMessage()); } } }
Output:
Map contains null values: null
Explanation:
- No Null Elements: The
Map.copyOf()
method ensures that the copied map does not containnull
keys or values. If the original map containsnull
, aNullPointerException
is thrown.
Real-World Example
Using Map.copyOf()
is beneficial when you want to share a map with other parts of your program while ensuring it remains unchanged.
Example with Fruit Prices:
import java.util.*; public class FruitPricesExample { public static void main(String[] args) { Map<String, Integer> fruitPrices = new HashMap<>(); fruitPrices.put("Mango", 50); fruitPrices.put("Banana", 20); fruitPrices.put("Apple", 70); // Create an unmodifiable copy of the fruit prices map Map<String, Integer> unmodifiableFruitPrices = Map.copyOf(fruitPrices); System.out.println("Unmodifiable Fruit Prices Map: " + unmodifiableFruitPrices); // Modify the original map fruitPrices.put("Orange", 60); System.out.println("Original Fruit Prices Map After Modification: " + fruitPrices); // Unmodifiable map remains unchanged System.out.println("Unmodifiable Fruit Prices Map After Modification: " + unmodifiableFruitPrices); // Attempt to modify the unmodifiable map try { unmodifiableFruitPrices.put("Grapes", 80); // This will throw UnsupportedOperationException } catch (UnsupportedOperationException e) { System.out.println("Cannot modify unmodifiableFruitPrices: " + e.getMessage()); } } }
Output:
Unmodifiable Fruit Prices Map: {Mango=50, Banana=20, Apple=70} Original Fruit Prices Map After Modification: {Mango=50, Banana=20, Apple=70, Orange=60} Unmodifiable Fruit Prices Map After Modification: {Mango=50, Banana=20, Apple=70} Cannot modify unmodifiableFruitPrices: null
Explanation:
- Immutable Map: The
Map.copyOf()
method creates a read-only copy of the fruit prices map, ensuring the copied map remains unchanged even after the original map is modified. - Attempt to Modify: Attempting to add a key-value pair to the unmodifiable map throws an
UnsupportedOperationException
.
Conclusion
The Map.copyOf()
method in Java 10 provides a straightforward way to create unmodifiable copies of maps. This feature is helpful for creating read-only views of maps, ensuring the original data remains safe from accidental modification.
Summary:
- Immutable Copy:
Map.copyOf()
creates a map that cannot be changed. - Shallow Copy: Only references are copied, not the key-value pairs themselves.
- No Null Keys or Values: The original map cannot contain
null
keys or values. - Read-Only: The resulting map is read-only, preventing any modifications.
By using Map.copyOf()
, you can create safe, immutable maps in your Java applications, making your code more robust and reliable.