Multiple choice technology programming languages

How does the set collection deal with duplicate elements?

  1. An exception is thrown if you attempt to add an element with a duplicate value.

  2. The add method returns false if you attempt to add an element with a duplicate value.

  3. A set may contain elements that return duplicate values from a call to the equals method.

  4. Duplicate values will cause an error at compile time.

Reveal answer Fill a bubble to check yourself
B Correct answer
Explanation

Set collections maintain uniqueness by contract. When Set.add() is called with a duplicate element (as determined by equals()), the method returns false and the set remains unchanged. No exception is thrown. This allows code to check whether the addition actually modified the set. Options A and C incorrectly suggest exception behavior or allowing duplicates.

AI explanation

A Set enforces uniqueness based on equals()/hashCode(), but it does this silently rather than by throwing — calling add() with a value that's already present simply returns false and leaves the set unchanged. No exception is thrown and there's no compile-time detection of duplicates, since uniqueness is a runtime property of the data, not the type.