Java Set copyOf()

In this guide, you will learn about the Set copyOf() method in Java programming and how to use it with an example.

1. Set copyOf() Method Overview

Definition:

The copyOf() method in the Set interface of Java is a static method that returns an unmodifiable Set containing the elements of the given Collection. The elements are in no particular order, even if the provided collection is a set.

Syntax:

static <E> Set<E> copyOf(Collection<? extends E> coll)

Parameters:

- coll: the collection from which elements are to be copied.

Key Points:

- The returned Set is unmodifiable, meaning any attempt to modify it will result in an UnsupportedOperationException.

- The method performs in linear time complexity, O(n), as it iterates over the provided collection.

- If the provided Collection is modified after the Set is created, the returned Set does not reflect such modifications.

- The method throws a NullPointerException if the given collection or any of its elements are null.

- The copyOf() method has been available since Java 9.

2. Set copyOf() Method Example

import java.util.HashSet;
import java.util.Set;

public class SetCopyOfExample {
    public static void main(String[] args) {
        Set<String> originalSet = new HashSet<>();
        originalSet.add("Dog");
        originalSet.add("Cat");
        originalSet.add("Bird");

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

        System.out.println("Original Set: " + originalSet);
        System.out.println("Copied Set: " + copiedSet);

        // Attempting to modify the copied set will throw UnsupportedOperationException
        try {
            copiedSet.add("Fish");
        } catch (UnsupportedOperationException e) {
            System.out.println("Exception: " + e.getMessage());
        }
    }
}

Output:

Original Set: [Bird, Cat, Dog]
Copied Set: [Bird, Cat, Dog]
Exception: UnsupportedOperationException

Explanation:

In this example, a HashSet named originalSet is created and populated with three string elements. 

The Set.copyOf() method is then used to create an unmodifiable copy of originalSet, named copiedSet. The contents of both the original and copied sets are printed to the console, showing that they contain the same elements. 

An attempt to add a new element to copiedSet is then made, demonstrating that the copied set is unmodifiable. This attempt results in an UnsupportedOperationException being thrown and caught, and the exception's message is printed to the console.

Comments