The unmodifiableCollection() method in Java is a utility method provided by the java.util.Collections class. It returns an unmodifiable view of the specified collection, meaning that any attempts to modify the collection through this view will result in an UnsupportedOperationException. This method is useful when you need to provide a read-only view of a collection, ensuring that the original collection remains unchanged.
Table of Contents
- Introduction
unmodifiableCollection()Method Syntax- Examples
- Basic Usage of
unmodifiableCollection() - Using
unmodifiableCollection()with Custom Classes
- Basic Usage of
- Real-World Use Case
- Conclusion
Introduction
The Collections.unmodifiableCollection() method allows you to create a read-only view of an existing collection. The returned collection does not allow any modifications such as adding, removing, or updating elements. This is useful in scenarios where you want to share a collection with other parts of your program without allowing them to alter it, ensuring data integrity and immutability.
unmodifiableCollection() Method Syntax
The syntax for the unmodifiableCollection() method is as follows:
public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c)
Parameters:
c: The collection for which an unmodifiable view is to be returned.
Returns:
- An unmodifiable view of the specified collection.
Throws:
NullPointerExceptionif the specified collection is null.
Examples
Basic Usage of unmodifiableCollection()
The following example demonstrates how to use the unmodifiableCollection() method to create a read-only view of a collection.
Example
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class UnmodifiableCollectionExample {
public static void main(String[] args) {
// Create a list with initial elements
List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
// Create an unmodifiable view of the list
Collection<String> unmodifiableCollection = Collections.unmodifiableCollection(list);
// Display the unmodifiable collection
System.out.println("Unmodifiable Collection: " + unmodifiableCollection);
// Attempt to modify the unmodifiable collection (will throw UnsupportedOperationException)
try {
unmodifiableCollection.add("Date");
} catch (UnsupportedOperationException e) {
System.out.println("Error: Cannot modify an unmodifiable collection");
}
// Display the original list after attempted modification
System.out.println("Original List: " + list);
}
}
Output:
Unmodifiable Collection: [Apple, Banana, Cherry]
Error: Cannot modify an unmodifiable collection
Original List: [Apple, Banana, Cherry]
Using unmodifiableCollection() with Custom Classes
You can also use the unmodifiableCollection() method with collections containing instances of custom classes.
Example
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
class Student {
String name;
Student(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
public class CustomUnmodifiableCollectionExample {
public static void main(String[] args) {
// Create a list of students
List<Student> students = new ArrayList<>();
students.add(new Student("Amit"));
students.add(new Student("Neha"));
students.add(new Student("Raj"));
// Create an unmodifiable view of the student list
Collection<Student> unmodifiableStudents = Collections.unmodifiableCollection(students);
// Display the unmodifiable student collection
System.out.println("Unmodifiable Student Collection: " + unmodifiableStudents);
// Attempt to modify the unmodifiable student collection (will throw UnsupportedOperationException)
try {
unmodifiableStudents.add(new Student("Vikram"));
} catch (UnsupportedOperationException e) {
System.out.println("Error: Cannot modify an unmodifiable student collection");
}
// Display the original student list after attempted modification
System.out.println("Original Student List: " + students);
}
}
Output:
Unmodifiable Student Collection: [Amit, Neha, Raj]
Error: Cannot modify an unmodifiable student collection
Original Student List: [Amit, Neha, Raj]
Explanation:
-
Unmodifiable View: The
unmodifiableCollection()method returns a read-only view of the specified collection, ensuring that any attempts to modify the collection through this view will result in anUnsupportedOperationException. -
Immutable Nature: The example shows that any modification attempts result in an exception, demonstrating the immutability of the unmodifiable collection.
-
Custom Class: The method works with custom class instances, allowing you to create unmodifiable views of collections containing user-defined objects.
Real-World Use Case
Providing Read-Only Access to a Collection
In real-world applications, the unmodifiableCollection() method can be used to provide read-only access to a collection, such as when returning a collection from a method that should not be modified by the caller.
Example
Imagine a scenario where you have a class that manages a collection of configuration settings, and you want to provide read-only access to the settings.
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
class Configuration {
private final List<String> settings;
public Configuration() {
settings = new ArrayList<>();
settings.add("timeout=30s");
settings.add("maxConnections=100");
settings.add("enableLogging=true");
}
// Method to get an unmodifiable view of the configuration settings
public Collection<String> getSettings() {
return Collections.unmodifiableCollection(settings);
}
}
public class ConfigurationExample {
public static void main(String[] args) {
Configuration config = new Configuration();
// Get the unmodifiable view of configuration settings
Collection<String> settings = config.getSettings();
// Display the configuration settings
System.out.println("Configuration Settings: " + settings);
// Attempt to modify the configuration settings (will throw UnsupportedOperationException)
try {
settings.add("newSetting=value");
} catch (UnsupportedOperationException e) {
System.out.println("Error: Cannot modify configuration settings");
}
}
}
Output:
Configuration Settings: [timeout=30s, maxConnections=100, enableLogging=true]
Error: Cannot modify configuration settings
Explanation:
-
Read-Only Access: The
getSettings()method returns an unmodifiable view of the configuration settings, ensuring that the settings cannot be modified externally. -
Immutable Collection: The example demonstrates the use of an unmodifiable collection to protect the integrity of configuration data.
Conclusion
The Collections.unmodifiableCollection() method is a powerful utility for creating unmodifiable (read-only) views of collections in Java. By providing a simple way to ensure immutability, it enhances the flexibility and safety of your code by preventing unintended modifications. This method is particularly valuable in scenarios where you need to protect the integrity of collections while providing access to them, improving the robustness and maintainability of your Java applications.