HashSet in Java
In the previous blog, we learned about the Concrete Collection in Java. If you want to know more about it visit Concrete Collections in Java - LinkedList . In this blog we will go through another Class in Collection called HashSet.
HashSet
In our previous blog, we have already seen that the LinkedList and array stored the elements in a sequential manner as per our convenience. But the drawback is that if we are trying to search for a particular element and we don’t remember the index position of that element then we need to visit through all the elements until we find that element. This task is time-consuming. But if we don’t care about the sequencing of the element, then there are data structures that can solve this problem and help to find the element much faster than LinkedList and array. The well known data structure that finds the elements quickly is called Hash Table. The hash table functionality is provided by the Class in the Collection Framework called HashSet. In order to create a HashSet, the first step we need to perform is to import the package java.util.HashSet.
Syntax of Creating a HashSet
Once the package is imported we can create the HashSet in the following way:
Syntax
Here the Type specifies the Type of the HashSet
e.g.
Importance of HashSet
We have already seen above that HashSet is mostly used when we want to access the elements randomly. The reason is that the elements in the hash table are accessed using the hash code. As the hash codes are unique in nature, the HashSet cannot contain duplicate elements.
Methods of HashSet
HashSet provides various methods that allow us to perform operations on Sets. We will go through those methods one by one
- add()
- addAll()
- iterator()
- remove()
- remove()
- retainAll()
- containsAll()
- contains()
- clone()
- clear()
- size()
- isEmpty()
add() method adds the specified element to the set if that element is not present in the Set.
e.g.
Output
addAll() method is used for adding all the specified elements of the collection to the Set.
e.g.
Output
iterator() method is used to access the elements of the hash set.
e.g.
Output
remove() method is used to remove or delete the specified element from the Set.
e.g.
Output
remove() methods removes or deletes all the elements of the set.
e.g.
Output
retainAll() is used when we want to perform set operations i.e. intersection. It performs the intersection between the two sets.
e.g.
Output
containsAll() method is used to verify whether the set is a subset of another set or not.
e.g.
Output
contains() method searches or finds the HashSet for the specified elements and returns the result either true or false.
clone() method is used to create a copy of the HashSet.
clear() method is used to remove or delete all the elements of the HashSet
size() method returns the size of the HashSet.
isEmpty() method is used for checking whether the HashSet is empty or not.
Example of the above methods:
e.g.
Output