Create Read-Only Map in Java

1. Introduction

In Java, creating read-only maps is crucial for ensuring data integrity by preventing modification of the map's contents after its creation. This immutability concept is particularly important in multi-threaded environments or when passing collections between methods or classes to avoid unintended side effects. Java provides various ways to create immutable or read-only maps, including the Collections utility class and the Map.of and Map.copyOf methods introduced in Java 9. This blog post will demonstrate how to create a read-only map in Java.

2. Program Steps

1. Create a read-only map using Collections.unmodifiableMap.

2. Create a read-only map using Map.of (Java 9 and later).

3. Attempt to modify the read-only maps to demonstrate their immutability.

3. Code Program

import java.util.*;

public class ReadOnlyMapExample {
    public static void main(String[] args) {
        // Step 1: Creating a read-only map using Collections.unmodifiableMap
        Map<Integer, String> originalMap = new HashMap<>();
        originalMap.put(1, "Apple");
        originalMap.put(2, "Banana");
        originalMap.put(3, "Cherry");
        Map<Integer, String> unmodifiableMap = Collections.unmodifiableMap(originalMap);
        System.out.println("Unmodifiable Map: " + unmodifiableMap);

        // Step 2: Creating a read-only map using Map.of (Java 9 and later)
        Map<Integer, String> readOnlyMap = Map.of(1, "Apple", 2, "Banana", 3, "Cherry");
        System.out.println("Read-Only Map using Map.of: " + readOnlyMap);

        // Step 3: Attempting to modify the read-only maps
        try {
            unmodifiableMap.put(4, "Date");
        } catch (UnsupportedOperationException e) {
            System.out.println("Cannot modify unmodifiableMap: UnsupportedOperationException");
        }

        try {
            readOnlyMap.put(4, "Date");
        } catch (UnsupportedOperationException e) {
            System.out.println("Cannot modify readOnlyMap using Map.of: UnsupportedOperationException");
        }
    }
}

Output:

Unmodifiable Map: {1=Apple, 2=Banana, 3=Cherry}
Read-Only Map using Map.of: {1=Apple, 2=Banana, 3=Cherry}
Cannot modify unmodifiableMap: UnsupportedOperationException
Cannot modify readOnlyMap using Map.of: UnsupportedOperationException

Explanation:

1. The program begins by creating a HashMap named originalMap and populating it with key-value pairs. This map is mutable.

2. An unmodifiable version of originalMap is created using Collections.unmodifiableMap(originalMap). This method returns a view of the original map that cannot be modified. Attempting to add, remove, or update elements in this map will result in an UnsupportedOperationException.

3. The program also demonstrates creating an immutable map using Map.of(1, "Apple", 2, "Banana", 3, "Cherry"), introduced in Java 9. Maps created with Map.of are inherently immutable.

4. Attempts to modify both the unmodifiable map created with Collections.unmodifiableMap and the immutable map created with Map.of result in UnsupportedOperationException, highlighting their read-only nature.

5. This example illustrates methods to create read-only maps in Java, ensuring data within a map remains constant after its creation, which is essential for maintaining data integrity in applications.

Comments