Java MCQ: What is the result of using the Java 9 method Set.of() with duplicate elements?
Answer:
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