Sobes.tech
Junior — Middle

Does the Set data structure store only unique elements?

sobes.tech AI

Answer from AI

Yes, the data structure Set in Java guarantees storing only unique elements. When adding a new element to a Set, a check is performed for the presence of the same element (using the equals() and hashCode() methods). If the element already exists, the addition does not occur, and the set remains free of duplicates.

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); // Outputs [apple, banana]
Does the Set data structure store only unique… - sobes.tech