Java List copyOf()

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

1. List copyOf() Method Overview

Definition:

The copyOf() method of the List interface in Java is a static method used to return an unmodifiable list containing the elements of the given Collection, in the order they are returned by the Collection's iterator.

Syntax:

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

Parameters:

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

Key Points:

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

- The method performs in linear time complexity, O(n), due to the internal use of an iterator over the provided collection.

- If the given Collection is subsequently modified, the returned list will not reflect such modifications.

- NullPointerException will be thrown if the given collection or any of its elements are null.

- The copyOf() method is available since Java 9.

2. List copyOf() Method Example

import java.util.ArrayList;
import java.util.List;

public class ListCopyOfExample {
    public static void main(String[] args) {
        List<String> originalList = new ArrayList<>();
        originalList.add("Apple");
        originalList.add("Banana");
        originalList.add("Cherry");

        // Creating an unmodifiable copy of the original list
        List<String> copiedList = List.copyOf(originalList);

        System.out.println("Original List: " + originalList);
        System.out.println("Copied List: " + copiedList);

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

Output:

Original List: [Apple, Banana, Cherry]
Copied List: [Apple, Banana, Cherry]
Exception: UnsupportedOperationException

Explanation:

In this example, an ArrayList named originalList is created and populated with three string elements. 

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

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

Comments