Which method introduced in Java 9 allows the creation of an immutable Set?

Java MCQ: Which method introduced in Java 9 allows the creation of an immutable Set?

a) Set.copyOf()
b) Set.of()
c) Set.unmodifiable()
d) Set.immutable()

Answer:

b) Set.of()

Explanation:

The Set.of() method, introduced in Java 9, allows the creation of an immutable Set. An immutable set is a set that cannot be modified after it is created, meaning that no elements can be added, removed, or changed.

Here’s an example of using Set.of():

import java.util.Set;

public class SetOfExample {
    public static void main(String[] args) {
        Set<String> fruits = Set.of("Apple", "Banana", "Cherry");
        System.out.println(fruits);

        // This will throw UnsupportedOperationException because the set is immutable
        // fruits.add("Mango");
    }
}

In this example, Set.of("Apple", "Banana", "Cherry") creates an immutable set containing three elements. Any attempt to modify the set (e.g., adding or removing elements) will result in an UnsupportedOperationException.

Set.of() is useful for creating small, fixed sets of elements where immutability is desired, ensuring that the set remains constant and unmodifiable throughout its lifetime.

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