HashSet in Java
What Is It?
A HashSet
is a collection in Java that stores unique elements, meaning no duplicates are allowed. It is implemented using a hash table, providing fast operations for adding, removing, and checking if an element is present.
How It WorksHashSet
uses the object’s hashCode
method to determine where the element is stored in the underlying hash table, making operations like searching, adding, and deleting very efficient, typically with constant time complexity.
Syntax for Creating a HashSet
Here’s how to create a HashSet
:
import java.util.HashSet;
HashSet setName = new HashSet<>();
//Syntax for declaring a HashSet with a specific data type
HashSet <Integer> numberSet = new HashSet<>();
//Example: Declaring a HashSet of integers
Explanation:
- Import the HashSet class from the util package to use it in your code.
- Use the generic syntax to specify the data type of elements that the HashSet will hold within the angle brackets (<>).
- Create an instance of the HashSet using the new keyword followed by the HashSet constructor without any arguments.
In the example, we declared a HashSet named numberSet, which will store integers.
Categorized HashSet methods in Java based on their operations.
- Adding Elements:
- add(E element): Adds the specified element to the HashSet if it is not already present.
- Removing Elements:
- remove(Object object): Removes the specified element from the HashSet if it is present.
- clear(): Removes all elements from the HashSet, making it empty.
- Checking Element Existence:
- contains(Object object): Checks if the HashSet contains the specified element.
- isEmpty(): Checks if the HashSet is empty.
- Size and Status:
- size(): Returns the number of elements in the HashSet.
- Collection Operations:
- addAll(Collection<? extends E> collection): Adds all elements from the specified collection to the HashSet.
- retainAll(Collection<?> collection): Retains only the elements that are present in the specified collection.
- containsAll(Collection<?> collection): Checks if the HashSet contains all the elements from the specified collection.
- removeAll(Collection<?> collection): Removes all elements from the HashSet that are present in the specified collection.
- Conversions and Views:
- toArray(): Converts the HashSet to an array.
- iterator(): Provides an iterator to iterate through the elements of the HashSet.
- Comparison and Equality:
- equals(Object object): Compares the HashSet with another object for equality.
- hashCode(): Returns the hash code value for the HashSet.
These methods allow you to perform various operations on a HashSet in Java, such as adding, removing, checking for elements, managing the size and status, and performing set operations like union, intersection, and difference with other collections. HashSet provides efficient and convenient ways to manage a collection of unique elements in Java without any duplicates.