1. Introduction
In Java, Collections API provides methods to create read-only collections. A read-only list is immutable, meaning that its elements cannot be modified, added, or removed once it is created. We can create a read-only list using the Collections.unmodifiableList() method.
2. Program Steps
1. Import necessary libraries.
2. Create a List.
3. Make the List read-only using Collections.unmodifiableList().
4. Try to modify the read-only list and catch the UnsupportedOperationException.
3. Code Program
// Step 1: Import necessary libraries
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ReadOnlyListExample {
public static void main(String[] args) {
// Step 2: Create a List
List<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
list.add("JavaScript");
// Step 3: Make the List read-only using Collections.unmodifiableList()
List<String> readOnlyList = Collections.unmodifiableList(list);
// Print the read-only list
System.out.println("Read-only List: " + readOnlyList);
// Step 4: Try to modify the read-only list and catch the UnsupportedOperationException
try {
readOnlyList.add("C++");
} catch (UnsupportedOperationException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
}
Output:
Read-only List: [Java, Python, JavaScript] Exception caught: null
4. Step By Step Explanation
Step 1: Import the necessary libraries for handling lists.
Step 2: Create a List named list and add some elements to it.
Step 3: Make the list read-only by using the Collections.unmodifiableList() method. The resulting readOnlyList cannot be modified.
Step 4: Try to add an element to the readOnlyList. This will throw an UnsupportedOperationException, which is caught and printed to the console.