The unmodifiableSet() method in Java is a utility method provided by the java.util.Collections class. It returns an unmodifiable view of the specified set, meaning that any attempts to modify the set through this view will result in an UnsupportedOperationException. This method is useful when you need to provide a read-only view of a set, ensuring that the original set remains unchanged.
Table of Contents
- Introduction
unmodifiableSet()Method Syntax- Examples
- Basic Usage of
unmodifiableSet() - Using
unmodifiableSet()with Custom Classes
- Basic Usage of
- Real-World Use Case
- Conclusion
Introduction
The Collections.unmodifiableSet() method allows you to create a read-only view of an existing set. The returned set does not allow any modifications such as adding, removing, or updating elements. This is useful in scenarios where you want to share a set with other parts of your program without allowing them to alter it, ensuring data integrity and immutability.
unmodifiableSet() Method Syntax
The syntax for the unmodifiableSet() method is as follows:
public static <T> Set<T> unmodifiableSet(Set<? extends T> s)
Parameters:
s: The set for which an unmodifiable view is to be returned.
Returns:
- An unmodifiable view of the specified set.
Throws:
NullPointerExceptionif the specified set is null.
Examples
Basic Usage of unmodifiableSet()
The following example demonstrates how to use the unmodifiableSet() method to create a read-only view of a set.
Example
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class UnmodifiableSetExample {
public static void main(String[] args) {
// Create a set with initial elements
Set<String> set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Cherry");
// Create an unmodifiable view of the set
Set<String> unmodifiableSet = Collections.unmodifiableSet(set);
// Display the unmodifiable set
System.out.println("Unmodifiable Set: " + unmodifiableSet);
// Attempt to modify the unmodifiable set (will throw UnsupportedOperationException)
try {
unmodifiableSet.add("Date");
} catch (UnsupportedOperationException e) {
System.out.println("Error: Cannot modify an unmodifiable set");
}
// Display the original set after attempted modification
System.out.println("Original Set: " + set);
}
}
Output:
Unmodifiable Set: [Apple, Cherry, Banana]
Error: Cannot modify an unmodifiable set
Original Set: [Apple, Cherry, Banana]
Using unmodifiableSet() with Custom Classes
You can also use the unmodifiableSet() method with sets containing instances of custom classes.
Example
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
class Student {
String name;
Student(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Student student = (Student) obj;
return name.equals(student.name);
}
@Override
public int hashCode() {
return name.hashCode();
}
}
public class CustomUnmodifiableSetExample {
public static void main(String[] args) {
// Create a set of students
Set<Student> students = new HashSet<>();
students.add(new Student("Amit"));
students.add(new Student("Neha"));
students.add(new Student("Raj"));
// Create an unmodifiable view of the student set
Set<Student> unmodifiableStudents = Collections.unmodifiableSet(students);
// Display the unmodifiable student set
System.out.println("Unmodifiable Student Set: " + unmodifiableStudents);
// Attempt to modify the unmodifiable student set (will throw UnsupportedOperationException)
try {
unmodifiableStudents.add(new Student("Vikram"));
} catch (UnsupportedOperationException e) {
System.out.println("Error: Cannot modify an unmodifiable student set");
}
// Display the original student set after attempted modification
System.out.println("Original Student Set: " + students);
}
}
Output:
Unmodifiable Student Set: [Neha, Amit, Raj]
Error: Cannot modify an unmodifiable student set
Original Student Set: [Neha, Amit, Raj]
Explanation:
-
Unmodifiable View: The
unmodifiableSet()method returns a read-only view of the specified set, ensuring that any attempts to modify the set 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 set.
-
Custom Class: The method works with custom class instances, allowing you to create unmodifiable views of sets containing user-defined objects.
Real-World Use Case
Providing Read-Only Access to a Set
In real-world applications, the unmodifiableSet() method can be used to provide read-only access to a set, such as when returning a set from a method that should not be modified by the caller.
Example
Imagine a scenario where you have a class that manages a set of configuration keys, and you want to provide read-only access to the keys.
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
class Configuration {
private final Set<String> configKeys;
public Configuration() {
configKeys = new HashSet<>();
configKeys.add("timeout");
configKeys.add("maxConnections");
configKeys.add("enableLogging");
}
// Method to get an unmodifiable view of the configuration keys
public Set<String> getConfigKeys() {
return Collections.unmodifiableSet(configKeys);
}
}
public class ConfigurationExample {
public static void main(String[] args) {
Configuration config = new Configuration();
// Get the unmodifiable view of configuration keys
Set<String> keys = config.getConfigKeys();
// Display the configuration keys
System.out.println("Configuration Keys: " + keys);
// Attempt to modify the configuration keys (will throw UnsupportedOperationException)
try {
keys.add("newKey");
} catch (UnsupportedOperationException e) {
System.out.println("Error: Cannot modify configuration keys");
}
}
}
Output:
Configuration Keys: [enableLogging, timeout, maxConnections]
Error: Cannot modify configuration keys
Explanation:
-
Read-Only Access: The
getConfigKeys()method returns an unmodifiable view of the configuration keys, ensuring that the keys cannot be modified externally. -
Immutable Set: The example demonstrates the use of an unmodifiable set to protect the integrity of configuration keys.
Conclusion
The Collections.unmodifiableSet() method is a powerful utility for creating unmodifiable (read-only) views of sets 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 sets while providing access to them, improving the robustness and maintainability of your Java applications.