HashSet in Java ensures uniqueness of elements by using a combination of the hashCode() and equals() methods. When you add an element to a HashSet, the HashSet first calculates the hash code of the element using the element's hashCode() method. It then uses the hash code to determine the index in the internal array where the element should be stored.
If there are no other elements at that index, the element is added to the HashSet and the HashSet ensures that it is unique. However, if there is already an element at that index, the HashSet uses the element's equals() method to compare the new element with the existing element. If the two elements are equal, the new element is not added to the HashSet since it is already present. If the two elements are not equal, the HashSet tries to find another index in the array for the new element.
Here is an example to demonstrate this:
import java.util.HashSet;
public class HashSetExample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
// Adding some elements to the HashSet
set.add("apple");
set.add("banana");
set.add("cherry");
set.add("apple"); // Duplicate element
// Printing the HashSet
System.out.println(set);
}
}
In this example, when we add the element "apple" to the HashSet for the second time, the HashSet will calculate the hash code of the element and use it to determine the index in the internal array. It will then use the equals() method to compare the new "apple" element with the existing "apple" element, and since they are equal, the new element will not be added to the HashSet. When we print the HashSet, the output will be:
[banana, apple, cherry]
As you can see, the HashSet contains only three elements and the duplicate element "apple" has been removed.