Sobes.tech
Junior — Middle

Is it allowed to have duplicate values within a Set collection?

sobes.tech AI

Answer from AI

In a Set collection in Java, duplicate values are not allowed. Set guarantees the uniqueness of elements, meaning each element can only appear once. If you try to add a duplicate, the add operation simply does not change the collection.

For example:

Set<String> set = new HashSet<>();
set.add("apple");
set.add("banana");
set.add("apple"); // will not be added, as "apple" already exists

System.out.println(set); // Will output [apple, banana]