Set.copyOf() in Java

Introduction

Java 10 introduced the Set.copyOf() method, which creates an unmodifiable copy of an existing set. This feature simplifies the process of creating read-only sets, ensuring that the set cannot be modified after its creation. The Set.copyOf() method is part of Java’s effort to enhance immutability and make code more concise and safe.

Key Points:

  • Immutable Copy: Set.copyOf() creates a set that cannot be changed.
  • Shallow Copy: The elements themselves are not cloned; only references are copied.
  • Null Safety: Set.copyOf() does not allow null elements in the source set.
  • Read-Only: Attempting to modify the resulting set will throw an UnsupportedOperationException.

How to Use Set.copyOf()

To create an unmodifiable set, you can use the Set.copyOf() method and pass an existing set to it.

Syntax:

Set<E> unmodifiableSet = Set.copyOf(originalSet);
  • originalSet: The original set from which to create the unmodifiable copy.
  • unmodifiableSet: The resulting read-only set.

Example of Using Set.copyOf()

Basic Example

Here’s a simple example demonstrating the use of Set.copyOf() with fruits:

import java.util.*;

public class SetCopyOfExample {
    public static void main(String[] args) {
        Set<String> originalSet = new HashSet<>(Arrays.asList("Mango", "Banana", "Apple"));

        // Create an unmodifiable copy of the original set
        Set<String> copySet = Set.copyOf(originalSet);

        System.out.println("Original Set: " + originalSet);
        System.out.println("Copy Set: " + copySet);

        // Attempt to modify the copy
        try {
            copySet.add("Grapes");  // This will throw UnsupportedOperationException
        } catch (UnsupportedOperationException e) {
            System.out.println("Cannot modify copySet: " + e.getMessage());
        }
    }
}

Output:

Original Set: [Mango, Banana, Apple]
Copy Set: [Mango, Banana, Apple]
Cannot modify copySet: null

Explanation:

  • Immutable Copy: The Set.copyOf() method creates a new set that is unmodifiable, ensuring the original set’s content cannot be altered.
  • UnsupportedOperationException: Any attempt to modify the resulting set will result in an UnsupportedOperationException.

Null Safety

The Set.copyOf() method does not allow null elements in the original set. If the original set contains null, a NullPointerException is thrown.

Example:

import java.util.*;

public class NullSafetyExample {
    public static void main(String[] args) {
        Set<String> originalSet = new HashSet<>(Arrays.asList("Mango", null, "Apple"));

        try {
            // Attempt to create an unmodifiable copy of a set with null elements
            Set<String> copySet = Set.copyOf(originalSet);
        } catch (NullPointerException e) {
            System.out.println("Set contains null elements: " + e.getMessage());
        }
    }
}

Output:

Set contains null elements: null

Explanation:

  • No Null Elements: The Set.copyOf() method ensures that the copied set does not contain null elements. If the original set contains null, a NullPointerException is thrown.

Real-World Example

Using Set.copyOf() is beneficial when you want to share a set with other parts of your program while ensuring it remains unchanged.

Example with Indian Names:

import java.util.*;

public class IndianNamesExample {
    public static void main(String[] args) {
        Set<String> names = new HashSet<>();
        names.add("Rajesh");
        names.add("Priya");
        names.add("Sneha");

        // Create an unmodifiable copy of the names set
        Set<String> unmodifiableNames = Set.copyOf(names);

        System.out.println("Unmodifiable Names Set: " + unmodifiableNames);

        // Modify the original set
        names.add("Kunal");
        System.out.println("Original Names Set After Modification: " + names);

        // Unmodifiable set remains unchanged
        System.out.println("Unmodifiable Names Set After Modification: " + unmodifiableNames);

        // Attempt to modify the unmodifiable set
        try {
            unmodifiableNames.add("Manisha");  // This will throw UnsupportedOperationException
        } catch (UnsupportedOperationException e) {
            System.out.println("Cannot modify unmodifiableNames: " + e.getMessage());
        }
    }
}

Output:

Unmodifiable Names Set: [Rajesh, Priya, Sneha]
Original Names Set After Modification: [Rajesh, Priya, Sneha, Kunal]
Unmodifiable Names Set After Modification: [Rajesh, Priya, Sneha]
Cannot modify unmodifiableNames: null

Explanation:

  • Immutable Set: The Set.copyOf() method creates a read-only copy of the names set, ensuring the copied set remains unchanged even after the original set is modified.
  • Attempt to Modify: Attempting to add an element to the unmodifiable set throws an UnsupportedOperationException.

Conclusion

The Set.copyOf() method in Java 10 provides a straightforward way to create unmodifiable copies of sets. This feature is helpful for creating read-only views of sets, ensuring the original data remains safe from accidental modification.

Summary:

  • Immutable Copy: Set.copyOf() creates a set that cannot be changed.
  • Shallow Copy: Only references are copied, not the elements themselves.
  • No Null Elements: The original set cannot contain null elements.
  • Read-Only: The resulting set is read-only, preventing any modifications.

By using Set.copyOf(), you can create safe, immutable sets in your Java applications, making your code more robust and reliable.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top