What is the result of using the Java 9 method Set.of() with duplicate elements?

Java MCQ: What is the result of using the Java 9 method Set.of() with duplicate elements?

a) It creates a Set with duplicate elements
b) It creates a Set with the duplicates removed
c) It throws an IllegalArgumentException
d) It sorts the elements and removes duplicates

Answer:

c) It throws an IllegalArgumentException

Explanation:

Using the Java 9 method Set.of() with duplicate elements results in an IllegalArgumentException. The Set.of() method is designed to create an immutable set, and since sets do not allow duplicate elements, attempting to include duplicates in the method call will cause an exception to be thrown.

Here’s an example that demonstrates this behavior:

import java.util.Set;

public class SetOfDuplicateExample {
    public static void main(String[] args) {
        // This will throw IllegalArgumentException due to duplicate elements
        Set<String> fruits = Set.of("Apple", "Banana", "Apple");
    }
}

In this example, the Set.of() method is called with duplicate elements (“Apple” appears twice). As a result, an IllegalArgumentException is thrown, indicating that the set cannot contain duplicate elements.

The strict enforcement of unique elements by Set.of() ensures that the resulting set is consistent with the expected behavior of a set, which is to contain no duplicate elements.

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