Introduce Java HashSet and give examples
A HashSet
in Java is a part of the Java Collections Framework and implements the Set
interface. It is used to store a collection of unique elements, meaning that it does not allow duplicate values. The HashSet
class is backed by a hash table, which provides constant time performance for basic operations like add, remove, and contains, assuming the hash function disperses the elements properly among the buckets.
HashSet
does not allow duplicate elements. If you try to add a duplicate, it will simply ignore the operation.HashSet
are not stored in any particular order. The order can change when elements are added or removed.HashSet
allows one null value.Here’s a simple example demonstrating the use of HashSet
in Java:
import java.util.HashSet;
public class HashSetExample {
public static void main(String[] args) {
// Create a HashSet
HashSet<String> set = new HashSet<>();
// Add elements to the HashSet
set.add("Apple");
set.add("Banana");
set.add("Orange");
set.add("Mango");
set.add("Apple"); // Duplicate element, will not be added
// Display the HashSet
System.out.println("HashSet: " + set);
// Check if an element exists
if (set.contains("Banana")) {
System.out.println("Banana is in the HashSet.");
} else {
System.out.println("Banana is not in the HashSet.");
}
// Remove an element
set.remove("Mango");
System.out.println("After removing Mango: " + set);
// Get the size of the HashSet
System.out.println("Size of HashSet: " + set.size());
// Clear the HashSet
set.clear();
System.out.println("After clearing, HashSet: " + set);
}
}
HashSet: [Banana, Orange, Apple, Mango]
Banana is in the HashSet.
After removing Mango: [Banana, Orange, Apple]
Size of HashSet: 3
After clearing, HashSet: []
HashSet
is a powerful and efficient way to store unique elements in Java. It is particularly useful when you need to ensure that no duplicates are present and when the order of elements is not important.