What does the List.copyOf() method introduced in Java 10 return?

Java MCQ: What does the List.copyOf() method introduced in Java 10 return?

a) A deep copy of the list
b) A shallow copy of the list
c) An unmodifiable copy of the list
d) A mutable copy of the list

Answer:

c) An unmodifiable copy of the list

Explanation:

The List.copyOf() method, introduced in Java 10, returns an unmodifiable copy of the specified list. This method creates a new list containing the elements of the provided list, but the new list is unmodifiable, meaning that any attempt to modify it (e.g., adding or removing elements) will result in an UnsupportedOperationException.

Here’s an example of using List.copyOf():

import java.util.List;

public class ListCopyOfExample {
    public static void main(String[] args) {
        List<String> originalList = List.of("Apple", "Banana", "Cherry");
        List<String> copyList = List.copyOf(originalList);

        System.out.println(copyList);

        // This will throw UnsupportedOperationException because the list is unmodifiable
        // copyList.add("Mango");
    }
}

In this example, List.copyOf(originalList) creates an unmodifiable copy of originalList. Any attempt to modify copyList will throw an UnsupportedOperationException.

The List.copyOf() method is useful when you need a read-only view of a list, ensuring that the contents of the copied list cannot be altered.

Reference links:

https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html

Leave a Comment

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

Scroll to Top