HashSet
HashSet in Java is a part of the java.util package and implements the Set interface. It is widely used when we need to store unique elements and do not care about the order in which they are stored.
Key Features of HashSet:
-
No Duplicate Elements: A
HashSetcannot contain duplicate elements, meaning it will automatically filter out any repeated values. -
Unordered: The elements are stored in no particular order. The order of insertion is not maintained, as
HashSetuses a hashing mechanism. -
Null Elements: A
HashSetcan contain at most onenullelement. -
Efficient Lookup: It provides constant-time performance for basic operations like
add,remove,contains, andsize, assuming the hash function disperses elements properly across the hash table. -
Underlying Data Structure: It uses a hash table for storage, meaning it internally relies on the hash code of objects to store and retrieve elements efficiently.
Common Methods:
add(E e): Adds the specified element to the set if it is not already present.remove(Object o): Removes the specified element from the set if it is present.contains(Object o): Returnstrueif the set contains the specified element.size(): Returns the number of elements in the set.isEmpty(): Checks if the set is empty.
Example Usage:
import java.util.HashSet;
public class HashSetExample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
// Add elements to the HashSet
set.add("Apple");
set.add("Banana");
set.add("Orange");
set.add("Banana"); // Duplicate element, will not be added
// Print the HashSet
System.out.println(set); // Output: [Apple, Orange, Banana] (Order may vary)
// Check if an element exists
System.out.println(set.contains("Apple")); // Output: true
// Remove an element
set.remove("Banana");
// Check the size of the set
System.out.println(set.size()); // Output: 2
}
}
Advantages:
- Fast lookups and inserts.
- No duplicates.
- Automatically manages the uniqueness of elements.
Limitations:
- Unordered, so if the order of elements matters, use a
LinkedHashSet. - Not thread-safe; for multithreaded environments, use
Collections.synchronizedSetorConcurrentHashMapwith a set view.