A HashSet
is part of Java’s collection framework and is an implementation of the Set
interface. It is a collection that doesn’t allow duplicate elements and stores them in an unordered way. It is backed by a hash table, which means it provides constant time complexity (O(1)) for the basic operations like add, remove, and contains, assuming the hash function disperses the elements properly.
Features
- No Duplicates: A
HashSet
automatically removes duplicate elements. If you try to add an element that’s already in the set, it will not be added again. - Unordered: The elements in a
HashSet
are not stored in any particular order. The order in which elements are added is not necessarily the order in which they are iterated. - Null Elements:
HashSet
allows onenull
element, unlike some other collection types. - Fast Performance: Because it uses a hash table, it performs most operations (like add, remove, and contains) in constant time O(1), making it efficient for large datasets.
Common Operations
- add(E e): Adds the specified element to the set if it’s not already present.
- remove(Object o): Removes the specified element from the set.
- contains(Object o): Checks if the set contains the specified element.
- size(): Returns the number of elements in the set.
- clear(): Removes all elements from the set.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import java.util.HashSet; public class HashSetExample { public static void main(String[] args) { // Create a HashSet HashSet<String> set = new HashSet<>(); // Adding elements to the set set.add("Java"); set.add("Python"); set.add("JavaScript"); // Trying to add a duplicate element set.add("Java"); // Will not be added // Displaying the set System.out.println(set); // Output: [Java, Python, JavaScript] // Checking if an element exists System.out.println(set.contains("Java")); // Output: true System.out.println(set.contains("C++")); // Output: false } } |
Use Cases
- When you need to store a collection of unique elements.
- When you do not care about the order of elements.
- When you need to perform fast lookups, additions, or deletions of elements.