Java MCQ: What does the List.copyOf() method introduced in Java 10 return?
Answer:
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