The collection framework provides two general-purpose Set implementations: Hashset and TreeSet. In this tutorial, we will learn HashSet in Java with example and programs in a very simple way. The HashSet class was introduced in Java 1.2 version and present in java.util.HashSet package. It internally uses HashMap to store the unique elements. It is much faster and gives constant time performance for insertion, removal, and retrieval operations. Let’s see in detail.
HashSet in Java
➲ HashSet class is an unordered collection of objects which contains the only unique element.
➲ HashSet internally uses HashMap to store its element by using a mechanism called hashing.
➲ It does not allow the duplicate elements. If you try to add a duplicate element in the HashSet, the older element would be overwritten.
➲ It allows only one null element. If you add more than one null element, it would still return only one null value.
➲ HashSet does not maintain any order in which the elements are added. The order of the elements will be unpredictable. It will return in any random order.
➲ HashSet is much faster due to the using of hashing technique and gives the constant-time performance for adding(insertion), retrieval, removal, contains, and size operations. Hashing provides the constant execution time for the method like add(), remove(), contains(), and size() even for the large set.
➲ The HashSet class is not synchronized that means it is not thread-safe. Therefore, multiple threads can use the same HashSet’s object at the same time and will not give deterministic final output. If you want to synchronize the HashSet, use Collections.synchronizeSet() method.
➲ The iterator returned by the HashSet class is fail-fast that means any modification happened in the HashSet during iteration, will throw ConcurrentModificationException.
Java HashSet Hierarchy
The HashSet class extends AbstractSet class and implements the Set interface. The AbstractSet class itself extends the AbstractCollection class. It also implements Cloneable and Serializable marker interfaces. The HashSet hierarchy diagram can be shown in the below picture.
HashSet class declaration
Let’s see the declaration for java.util.HashSet class.
public class HashSet
Constructors of Java HashSet class
The following constructors are defined for Java HashSet class:
1. HashSet(): It constructs an empty hash set. i.e. default hash set. The default capacity is 16.
2. HashSet(int initialCapacity): It initializes the capacity of the HashSet. When the set capacity reaches full and a new element is added, the capacity of the hash set is expended automatically. The internal structure will double in size before adding a new element.
3. HashSet(int initialCapacity, float fillRatio): It initializes the capacity and the fill ratio(also called load factor or load capacity) of the hash set. When the number of elements is greater than the capacity of the HashSet, the size of the hash set is grown automatically by multiplying the capacity with the load factor. The default value of the load factor is 0.75. The value of the fill ratio ranges from 0.0 to1.0.
4. HashSet(Collection c): It initializes the hash set by using the elements of c. This constructor acts as a copy constructor. It copies the elements from one collection into the newly created collection. We cannot provide a custom initial capacity or fill ratio. If the original collection had duplicate elements, only one duplicate element will be allowed in the final created set.
Note: The constructors that do not take a load factor, 0.75 is used.
Methods of Java HashSet class
The HashSet class does not define any additional methods. It inherits the methods of its parent classes and the methods of the implemented interface. The various methods provided by its superclasses and interfaces are as follows:
1. Adding a single element
If you want to add a single element, call the add() method.
Syntax:
public boolean add(Object o)
The add() method takes a single argument of the element to add. This method returns true if the set does not already contain a specified element.
2. Adding another collection of elements
If you want to add a group of elements from another collection to the set, call addAll() method.
Syntax:
public boolean addAll(Collection c)
Each element in the collection will be added to the current set via calling add() method on each element. It returns true if the current set changes. If no elements are added, false is returned. A UnsupportedOperationException will be thrown when a current set does not support adding elements.
3. Removing Single Element
If you wish to remove a single element at a time, use the remove() method.
Syntax:
public boolean remove(Object o)
To remove an element from the set, Set internally use equals() method for each element. If the element is found, the element is removed from the set and returns true. If not found, false is returned. If the removal is not supported, you will get UnsupportedOperationException.
4. Removing all elements
To remove all the elements from a set, use clear() method.
Syntax:
public void clear() // It returns nothing.
5. Checking for Existing element
To check a specific element is present or not in the set, use contains() method.
Syntax:
public boolean contains(Object element)
If the specified element is found in the set, it returns true otherwise false. The equality checking is done through the element’s equal method.
6. Checking size
If you wish to know how many elements are in a set, call size() method.
Syntax:
public int size()
7. Checking for Empty
If you wish to check that whether the HashSet contains elements or not.
Syntax:
public boolean isEmpty()
8. Coping and Cloning sets
Since the HashSet implements the Cloneable interface. So we can create a shallow copy of that hash set by calling the clone() method of the hash set.
Java HashSet Example Program
How to Add an Element to a Java HashSet
1. In this example program, we will see how to:
➧ Create a HashSet object.
➧ Adding elements to the hash set.
➧ Adding of the duplicate element will be ignored.
➧ Adding of the null element.
Program source code 1:
package hashSetTest; import java.util.HashSet; public class HashSetExample1 { public static void main(String[] args) { // Create a HashSet object. HashSet
How to Add Elements from an Existing Collection to a Java HashSet
2. In this program, we will learn how to add all the elements from an existing collection to a HashSet.
Program source code 2:
package hashSetTest; import java.util.ArrayList; import java.util.HashSet; public class HashSetExample2 { public static void main(String[] args) { // Create a ArrayList object. ArrayList
How to Remove Elements from a Java HashSet
3. This example program will show you how to:
➧ Remove a specific element from a HashSet.
➧ Remove all elements available in a Set.
Program source code 3:
package hashSetTest; import java.util.HashSet; public class HashSetExample3 { public static void main(String[] args){ // Create a HashSet object. HashSet
How to check Number of Elements in a Java HashSet
4. In this program, we will see how to:
➧ Find the number of elements in a set.
➧ Check a HashSet is empty or not.
Program source code 4:
package hashSetTest; import java.util.HashSet; import java.util.Set; public class HashSetExample4 { public static void main(String[] args) { Set
How to check an Existing Element in Java HashSet
5. This example program will show you how to check an element exists in the Java hash set or not. We will use contains() method for this.
Program source code 5:
package hashSetTest; import java.util.HashSet; import java.util.Set; public class HashSetExample4 { public static void main(String[] args) { Set
How to create User-defined Object of HashSet in Java
6. In this program, we will learn to create a user-defined object of HashSet in Java.
Program source code 6:
package hashSetTest; public class Student { // Declare instance variables. String name, sName; int id; public Student(String name, String sName, int id) { this.name = name; this.sName = sName; this.id=id; } } package hashSetTest; import java.util.HashSet; public class HashSetExample6 { public static void main(String[] args) { // Create a user-defined HashSet object of type Student. HashSet
Output: Ricky DAV 9876 John RSVM 10 Shubh DPS 1234
When to use HashSet in Java
HashSet in Java is used when:
1. We don’t want to store duplicate elements.
2. We want to remove duplicate elements from the list.
3. HashSet is more preferred when add and remove operatons are more as compared to get operations.
4. We are not working in the multithreading environment.
Final words
We hope that this article has covered almost all the important topics with practical example and programs related to the Java HashSet. All the programs are very important for begginers.
Thanks for reading. Have a good day!
The post Java HashSet | Example & Programs appeared first on Scientech Easy.