Practical Guide for HashSet in Java: Example and Use Cases
In this article, we will discuss HashSet in Java, its internal working, the constructors of HashSet, and different methods. Later in the article, we will also discuss how to perform different operation on HashSet with the help of examples.
Introduction
If we want to represent a group of individual objects where duplicates are not allowed and insertion order is not preserved, then we should go for Set. Set is a child interface of Collections in Java. If you do not become aware of Java collections, please check the below link for an understanding.
Must Check: What is Java?
Must Check: Top Java Online Courses & Certifications
Best-suited Java courses for you
Learn Java with these high-rated online courses
What is HashSet?
HashSet is a class that implements the Set interface. The underline data structure of HashSet is Hashtable. There are some important key points about HashSet, which are listed below.
- Duplicate elements are not allowed in HashSet.
- Elements put inside HashSet are based on hashcode; that’s why insertion order is not preserved.
- HashSet allows a null value.
- HashSet is a non-synchronized class, and hence it is not thread-safe
- Elements in HashSet are stored based on hashcode; because of this, HashSet is the best choice for searching operations.
- HashSet Implements Serializable and Clonable interfaces.
- The initial default capacity of HashSet is 16, and the load factor (fill ratio) is 0.75, meaning the size of HashSet increases when it is filled by 75%.
Internal working of HashSet
HashSet uses HashMap internally for the creation and addition of objects or elements. Observe the below code to understand it carefully.
When we internally create an object for HashSet, the HashMap object is created with a reference map. Now, if we add an element in HashSet, then internally, that element is put inside the map as a key. As we know, in HashMap key must be unique. Observe the below code to understand it. Let’s add fruits in HashSet and understand how it is internally implemented.
HashMap contains keys and values after insertions are performed.
Key | Value |
apple | PRESENT |
banana | PRESENT |
Since in HashMap key must be unique so duplicates are not allowed, and the hence same case is for HashSet duplicates are not allowed in HashSet.
Must Check: HashMap in Java
Declaration of HashSet
HashSet<Type> hashset_reference = new HashSet<>();
Note: To use HashSet in the program, we must have to import package like import java.util.HashSet
Constructor of HashSet
Constructor | Description |
HashSet() | It create HashSet with default initial capacity and load factor. |
HashSet(int capacity) | It create HashSet with defined capacity in integer. |
HashSet(int capacity, float loadFactor) | It create HashSet with defined capacity and load factor |
HashSet(Collection c) | It create HashSet and initialize it with elements of Collection |
Methods in HashSet
Methods | Description |
add( E e ) | Add element is HashSet if it is not already present |
remove( Object ) | To remove element if it is present inside HashSet |
clear() | It is use to delete all the elements from the HashSet |
size() | Return the size of the HashSet |
isEmpty() | Return true if HashSet is empty |
contains(Object) | Return true if HashSet contains the specified element |
iterator() | It is used to traverse over elements in the HashSet |
Operations on HashSet
To better understand HashSet in Java, let’s perform some basic operations on HashSet. Some commonly used HashSet operations are:
Add Element in HashSet
Let’s take an example of service-based companies and add them to HashSet using add() method.
Program:
import java.util.HashSet;
public class Company{ public static void main(String args[]) { // Creating HashSet object with reference companies HashSet<String> companies =new HashSet<>(); //Adding service based companies to HashSet companies.add("Tcs"); companies.add("Accenture"); companies.add("Cognizant"); companies.add("Infosys"); companies.add("Wipro"); // Printing HashSet of companies //Also note that order of element in HashSet is different then insertion order System.out.println(companies); }}
Output:
In the above program, we added service-based companies like Tcs , Accenture, Cognizant, Infosys, and Wipro into HashSet. As we discussed earlier, insertion order is not preserved in HashSet because, for each element, a hash code is calculated, which determines the index of specific elements inside the HashSet; hence the output is not print elements as per insertion order.
Access Element from HashSet
There are three different ways by which we can get elements from HashSet.
Using Array
Let’s take the above example program and access the element from HashSet by converting HashSet into Array. Once we have an array, then we can easily get elements by index. Here, we are accessing the element, which is at index 3.
Program:
import java.util.HashSet;
public class Company{ public static void main(String args[]) { // Creating HashSet object with reference companies HashSet<String> companies =new HashSet<>(); //Adding service based companies to HashSet //Also note that order of element in HashSet is different then insertion order companies.add("Tcs"); companies.add("Accenture"); companies.add("Cognizant"); companies.add("Infosys"); companies.add("Wipro"); // Printing HashSet of companies System.out.println(companies); // Converting HashSet into Array String[] array=companies.toArray( new String[companies.size()]); // Printing Company which is at index 3 System.out.println("Element at index 3 is:"+ array[3]); }}
Output:
Using for each loop
In this example program, we are accessing elements using each loop and printing the element which is at index 2.
Program:
import java.util.HashSet;
public class Company{ public static void main(String args[]) { // Creating HashSet object with reference companies HashSet<String> companies =new HashSet<>(); //Adding service based companies to HashSet companies.add("Tcs"); companies.add("Accenture"); companies.add("Cognizant"); companies.add("Infosys"); companies.add("Wipro"); // Printing HashSet of companies //Also note that order of element in HashSet is different then insertion order System.out.println(companies); int curr_index=0; int expected_index=2; // Use for each loop for traversing in companies for(String company: companies) { if(curr_index==expected_index) { // Printing Company which is at index 2 System.out.println("Element at index 2 is:"+ company); } curr_index++; } }}
Output:
Using an ArrayList
In this example program, we are accessing the element by converting HashSet into ArrayList and then accessing the element using get() method of ArrayList. Here, we are printing an element that is at index 4.
Program:
import java.util.ArrayList;import java.util.HashSet;
public class Company{ public static void main(String args[]) { // Creating HashSet object with reference companies HashSet<String> companies =new HashSet<>(); //Adding service based companies to HashSet companies.add("Tcs"); companies.add("Accenture"); companies.add("Cognizant"); companies.add("Infosys"); companies.add("Wipro"); // Printing HashSet of companies //Also note that order of element in HashSet is different then insertion order System.out.println(companies); // Converting HashSet into ArrayList ArrayList<String> alist=new ArrayList<>(companies); //Printing element which is at index 4 in ArrayList System.out.println("Element at index 4 is:"+alist.get(4)); }}
Output:
Remove Element from HashSet
In the below program, we remove element “Cognizant “ from HashSet.
Program:
import java.util.HashSet;
public class Company{ public static void main(String args[]) { // Creating HashSet object with reference companies HashSet<String> companies =new HashSet<>(); //Adding service based companies to HashSet companies.add("Tcs"); companies.add("Accenture"); companies.add("Cognizant"); companies.add("Infosys"); companies.add("Wipro"); // Printing HashSet of companies //Also note that order of element in HashSet is different then insertion order System.out.println(companies); // Removing element Cognizant from HashSet companies.remove("Cognizant"); // Printing HashSet of companies System.out.println("After removal of Cognizant HashSet contains:"+ companies); }}
Output:
Iterate Through a HashSet
The below program uses an Iterator of type String to use Next() or next() method to traverse through HashSet and prints elements that are present in HashSet.
Program:
import java.util.HashSet;import java.util.Iterator;
public class Company{ public static void main(String args[]) { // Creating HashSet object with reference companies HashSet<String> companies =new HashSet<>(); //Adding service based companies to HashSet companies.add("Tcs"); companies.add("Accenture"); companies.add("Cognizant"); companies.add("Infosys"); companies.add("Wipro"); //Creating Iterator of type String Iterator<String> itr=companies.iterator(); System.out.println("Elements in HashSet are:"); //hasNext() method is used here to whether element is present in HashSet or not.It return true or false while(itr.hasNext()) { //next() method used to traverse and prints elements from HashSet System.out.println( itr.next()); } }}
Output:
Conclusion
In this article, we have discussed HashSet in Java, it’s internal working, constructors of HashSet, and different methods. Later in the article, we have also discussed how to perform different operation on HashSet with the help of examples.
Hope, you will like the article.
Contributed By: Shubham Kumar
This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio