Junior — Middle
Why is there no repetition of elements in the Set data structure?
sobes.tech AI
Answer from AI
In Java, the data structure Set does not allow duplicate elements due to its internal mechanism for checking uniqueness. When adding a new element, Set uses the equals() and hashCode() methods to determine if such an element already exists in the collection. If an element with the same hash code and equality already exists, the new one is not added.
For example, in HashSet, elements are stored in a hash table where the key is the element itself. This ensures fast lookup and prevents duplication.
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); // [apple, banana]