HashSet implements the Set interface in Java using a hash table as its underlying data structure. It maintains a collection of unique elements, preventing duplicate entries from being stored.
Each element in a HashSet is associated with a unique key derived from its hashCode() method. This hash value serves as an index for storing and retrieving elements, enabling efficient access operations.
When adding an element, HashSet first computes its hash code. If the corresponding bucket is empty, the element is stored directly. If the bucket already contains an element, HashSet compares the new element with existing ones using equals(). Only if the elements are not equal will the new element be added to the collection.
The primary advantage of HashSet is its constant-time performance for basic operations like add, remove, and contains. However, it does not maintain insretion order, and performance depends heavily on the quality of the hash function implementation.
import java.util.HashSet;
public class HashSetDemo {
public static void main(String[] args) {
HashSet<String> items = new HashSet<>();
items.add("Java");
items.add("Python");
items.add("JavaScript");
System.out.println(items.contains("Java"));
System.out.println(items.contains("Ruby"));
items.remove("Python");
for (String language : items) {
System.out.println(language);
}
System.out.println(items.size());
}
}
Output:
true
false
Java
JavaScript
2