Introduction
The Set.copyOf()
method was introduced in Java 10 to allow you to create an unmodifiable copy of an existing set. This method ensures that the resulting set cannot be modified, meaning no elements can be added, removed, or altered. Any attempt to modify the set will throw an UnsupportedOperationException
.
The Set.copyOf()
method ensures immutability, making it useful when you need to provide a read-only view of a set. The method does not accept null
values, and it will throw a NullPointerException
if the source set contains null
.
Program Steps
- Create a Set: Create a mutable set of elements.
- Use
Set.copyOf()
: Create an unmodifiable copy of the original set. - Attempt Modifications: Try to modify the unmodifiable set, which will result in an exception.
- Display the Set: Print the contents of the copied set.
Java Program
Example 1: Copying a Set of Strings
import java.util.Set;
import java.util.HashSet;
public class SetCopyOfExample {
public static void main(String[] args) {
// Step 1: Create a mutable set of strings
Set<String> originalSet = new HashSet<>();
originalSet.add("Apple");
originalSet.add("Banana");
originalSet.add("Orange");
// Step 2: Create an unmodifiable copy of the set
Set<String> unmodifiableSet = Set.copyOf(originalSet);
// Step 3: Display the unmodifiable set
System.out.println("Unmodifiable Set: " + unmodifiableSet);
// Step 4: Attempt to modify the unmodifiable set (This will throw an exception)
try {
unmodifiableSet.add("Grapes");
} catch (UnsupportedOperationException e) {
System.out.println("Error: Cannot modify an unmodifiable set");
}
}
}
Output
Unmodifiable Set: [Banana, Orange, Apple]
Error: Cannot modify an unmodifiable set
Explanation
Step 1: Create a Mutable Set
A mutable set originalSet
is created using HashSet
:
Set<String> originalSet = new HashSet<>();
originalSet.add("Apple");
originalSet.add("Banana");
originalSet.add("Orange");
The set contains three strings: "Apple", "Banana", and "Orange". This set is mutable, meaning elements can be added or removed.
Step 2: Use Set.copyOf()
to Create an Unmodifiable Set
We use the Set.copyOf()
method to create an unmodifiable copy of originalSet
:
Set<String> unmodifiableSet = Set.copyOf(originalSet);
The unmodifiableSet
is now an immutable version of originalSet
. Any attempt to modify it will result in an UnsupportedOperationException
.
Step 3: Display the Unmodifiable Set
The program prints the unmodifiable set:
System.out.println("Unmodifiable Set: " + unmodifiableSet);
Output:
Unmodifiable Set: [Banana, Orange, Apple]
The elements are printed in no specific order (because a Set
does not guarantee element order).
Step 4: Attempt to Modify the Unmodifiable Set
Next, the program tries to add an element ("Grapes") to the unmodifiable set, which causes an UnsupportedOperationException
:
try {
unmodifiableSet.add("Grapes");
} catch (UnsupportedOperationException e) {
System.out.println("Error: Cannot modify an unmodifiable set");
}
Output:
Error: Cannot modify an unmodifiable set
Example 2: Copying a Set of Integers
import java.util.Set;
import java.util.HashSet;
public class SetCopyOfIntegerExample {
public static void main(String[] args) {
// Step 1: Create a mutable set of integers
Set<Integer> originalSet = new HashSet<>();
originalSet.add(1);
originalSet.add(2);
originalSet.add(3);
// Step 2: Create an unmodifiable copy of the set
Set<Integer> unmodifiableSet = Set.copyOf(originalSet);
// Step 3: Display the unmodifiable set
System.out.println("Unmodifiable Integer Set: " + unmodifiableSet);
// Step 4: Attempt to modify the unmodifiable set (This will throw an exception)
try {
unmodifiableSet.add(4);
} catch (UnsupportedOperationException e) {
System.out.println("Error: Cannot modify an unmodifiable integer set");
}
}
}
Output
Unmodifiable Integer Set: [1, 2, 3]
Error: Cannot modify an unmodifiable integer set
Explanation
- Original Set: A mutable set of integers
1
,2
, and3
. - Unmodifiable Set:
Set.copyOf()
creates an immutable copy oforiginalSet
. - Modification Attempt: An attempt to modify the unmodifiable set throws an
UnsupportedOperationException
.
Example 3: Copying a Set of Custom Objects
import java.util.Set;
import java.util.HashSet;
public class SetCopyOfCustomObjectExample {
public static void main(String[] args) {
// Step 1: Create a mutable set of Employee objects
Set<Employee> originalSet = new HashSet<>();
originalSet.add(new Employee("Ravi", 30));
originalSet.add(new Employee("Amit", 28));
originalSet.add(new Employee("Pooja", 35));
// Step 2: Create an unmodifiable copy of the set
Set<Employee> unmodifiableSet = Set.copyOf(originalSet);
// Step 3: Display the unmodifiable set
System.out.println("Unmodifiable Employee Set: " + unmodifiableSet);
// Step 4: Attempt to modify the unmodifiable set (This will throw an exception)
try {
unmodifiableSet.add(new Employee("Neha", 27));
} catch (UnsupportedOperationException e) {
System.out.println("Error: Cannot modify an unmodifiable employee set");
}
}
}
class Employee {
private String name;
private int age;
public Employee(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return name + " (" + age + ")";
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employee employee = (Employee) o;
return age == employee.age && name.equals(employee.name);
}
@Override
public int hashCode() {
return name.hashCode() + age;
}
}
Output
Unmodifiable Employee Set: [Ravi (30), Amit (28), Pooja (35)]
Error: Cannot modify an unmodifiable employee set
Explanation
- Original Set: A mutable set of
Employee
objects. - Unmodifiable Set:
Set.copyOf()
creates an immutable copy of the set. - Modification Attempt: Attempting to add a new
Employee
object results in anUnsupportedOperationException
.
Conclusion
The Set.copyOf()
method in Java 10 provides a simple way to create unmodifiable sets from existing sets. It ensures that the copied set cannot be modified, making it useful for creating immutable collections. The method can be used with any type of object (e.g., strings, integers, custom objects). Any attempts to modify the unmodifiable set will throw an UnsupportedOperationException
, ensuring that the set remains immutable throughout its lifecycle.
Comments
Post a Comment
Leave Comment