Create Read-Only Set in Java

1. Introduction

In Java, creating a read-only set is essential when you want to ensure that a set's contents remain unchanged throughout the lifecycle of an application. A read-only or unmodifiable set guarantees that no modifications can be made to the set, such as adding or removing elements, after its creation. This feature is particularly useful for maintaining data integrity and preventing accidental changes. Java provides mechanisms to create unmodifiable sets, including using the Collections utility class and the Set.of method introduced in Java 9. This blog post will demonstrate how to create read-only sets in Java.

2. Program Steps

1. Create a read-only set using Collections.unmodifiableSet.

2. Create a read-only set using Set.of (available from Java 9 onwards).

3. Attempt to modify the read-only sets to illustrate their immutability.

3. Code Program

import java.util.*;

public class ReadOnlySetExample {
    public static void main(String[] args) {
        // Creating a mutable set
        Set<String> mutableSet = new HashSet<>(Arrays.asList("Apple", "Banana", "Cherry"));

        // Step 1: Creating a read-only set using Collections.unmodifiableSet
        Set<String> unmodifiableSet = Collections.unmodifiableSet(mutableSet);
        System.out.println("Unmodifiable Set: " + unmodifiableSet);

        // Step 2: Creating a read-only set using Set.of (Java 9 and later)
        Set<String> readOnlySet = Set.of("Apple", "Banana", "Cherry");
        System.out.println("Read-Only Set using Set.of: " + readOnlySet);

        // Step 3: Attempting to modify the read-only sets
        try {
            unmodifiableSet.add("Date");
        } catch (UnsupportedOperationException e) {
            System.out.println("Cannot modify unmodifiableSet: UnsupportedOperationException");
        }

        try {
            readOnlySet.add("Date");
        } catch (UnsupportedOperationException e) {
            System.out.println("Cannot modify readOnlySet using Set.of: UnsupportedOperationException");
        }
    }
}

Output:

Unmodifiable Set: [Apple, Banana, Cherry]
Read-Only Set using Set.of: [Apple, Banana, Cherry]
Cannot modify unmodifiableSet: UnsupportedOperationException
Cannot modify readOnlySet using Set.of: UnsupportedOperationException

Explanation:

1. The program starts by creating a mutable HashSet named mutableSet and populating it with some elements. HashSet allows modifications such as adding or removing elements.

2. An unmodifiable version of mutableSet is created using Collections.unmodifiableSet(mutableSet). This method returns a view of the original set that cannot be modified. Attempting to add or remove elements from this set results in an UnsupportedOperationException.

3. The program also demonstrates creating a read-only set using Set.of("Apple", "Banana", "Cherry"), which is a feature introduced in Java 9. Sets created with Set.of are inherently unmodifiable and cannot be altered after their creation.

4. Attempts to add elements to both the unmodifiable set created with Collections.unmodifiableSet and the read-only set created with Set.of result in UnsupportedOperationException, demonstrating the immutability of these sets.

5. This example highlights two approaches to creating read-only sets in Java, showcasing how to enforce immutability to ensure the set's contents remain unchanged.

Comments