1. Introduction
In Java, you can create a read-only Set using the Collections.unmodifiableSet() method. A read-only Set is immutable, meaning that once it is created, you cannot modify its content by adding, removing, or altering the elements.
2. Program Steps
1. Import the necessary libraries.
2. Create a Set and populate it with elements.
3. Create a read-only Set using the Collections.unmodifiableSet() method.
4. Attempt to modify the read-only Set and handle the resulting UnsupportedOperationException.
3. Code Program
// Step 1: Import necessary libraries
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class ReadOnlySetExample {
public static void main(String[] args) {
// Step 2: Create a Set and populate it with elements
Set<String> set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Cherry");
// Step 3: Create a read-only Set using Collections.unmodifiableSet()
Set<String> readOnlySet = Collections.unmodifiableSet(set);
// Print the read-only set
System.out.println("Read-only Set: " + readOnlySet);
// Step 4: Attempt to modify the read-only Set and handle the resulting UnsupportedOperationException
try {
readOnlySet.add("Dragon Fruit");
} catch (UnsupportedOperationException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
}
Output:
Read-only Set: [Banana, Cherry, Apple] Exception caught: null
4. Step By Step Explanation
Step 1: Import the necessary libraries required for handling sets.
Step 2: Create a Set named set and populate it with some fruit names.
Step 3: Use the Collections.unmodifiableSet() method to make the set read-only. The resulting readOnlySet cannot be modified.
Step 4: An attempt to add an element to the readOnlySet throws an UnsupportedOperationException, which is caught and its message is printed to the console.