The Java HashSet is a powerful implementation of the Set Interface that stores unique elements in a hash table. It's part of the Java Collections Framework and provides constant-time performance for basic operations like add, remove, and contains.
To use a HashSet, first import it from the java.util package. Then, you can create an instance as follows:
import java.util.HashSet;
HashSet<String> fruits = new HashSet<>();
Use the add() method to insert elements into the HashSet:
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
fruits.add("Apple"); // This won't be added as it's a duplicate
The remove() method eliminates specified elements from the set:
fruits.remove("Banana");
Utilize the contains() method to verify if an element exists in the set:
boolean hasCherry = fruits.contains("Cherry"); // Returns true
You can iterate through a HashSet using an Iterator or a for-each loop:
// Using Iterator
Iterator<String> iterator = fruits.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
// Using for-each loop
for (String fruit : fruits) {
System.out.println(fruit);
}
HashSet is ideal for scenarios where you need to:
Feature | HashSet | ArrayList | LinkedList |
---|---|---|---|
Duplicates | No | Yes | Yes |
Order | Unordered | Ordered | Ordered |
Performance | O(1) for basic operations | O(1) for access, O(n) for insertion/deletion | O(1) for insertion/deletion, O(n) for access |
Java HashSet is a versatile and efficient collection for managing unique elements. Its constant-time performance for basic operations makes it an excellent choice for many applications. By understanding its features and best practices, you can leverage HashSet to optimize your Java programs effectively.