Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Java HashSet | Example & Programs

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 HashSetextends AbstractSetimplements Set, Cloneable, Serializable. 

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. 

Syntax:
    public Object clone()
 
9. Checking for Equality
The HashSet class defines equality by using equals() method on each element within the set.
Syntax:
    public boolean equals(Object o)
 
10. Hashing Collections
The HashSet class overrides the hashCode() method to define an appropriate hash code value for the set. It returns the same hash code by sum up all hash codes of all the elements. 
Syntax:
      public int hashCode() 

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 set=new HashSet(); // Adding elements to the hash set. set.add(“First”); set.add(“Second”); set.add(“Third”); set.add(“Fourth”); set.add(“Fifth”); // Adding of duplicate elements will be ignored. set.add(“First”); set.add(“Third”); // Adding of null elements. set.add(null); set.add(null); // Ignored. System.out.println(“Unordered and No Duplicate HashSet Elements”); System.out.println(set); } } Output: Unordered and No Duplicate HashSet Elements [null, Second, Third, First, Fourth, Fifth]

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 al=new ArrayList(); // Adding elements to the hash set. al.add(“Monday”); al.add(“Tuesday”); al.add(“Wednesday”); al.add(“Thursday”); al.add(“Friday”); // Adding duplicate elements. al.add(“Monday”); al.add(“Friday”); System.out.println(“Original Elements Order “); System.out.println(al); // Create a HashSet object. HashSet hset=new HashSet(); // Call addAll() method for Adding all the elements from an existing collection to a HashSet. hset.addAll(al); System.out.println(“Unordered HashSet Elements without Duplicate elements”); System.out.println(hset); } } Output: Original Elements Order [Monday, Tuesday, Wednesday, Thursday, Friday, Monday, Friday] Unordered HashSet Elements without Duplicate elements [Monday, Thursday, Friday, Wednesday, Tuesday]

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 hset=new HashSet(); hset.add(5); hset.add(10); hset.add(15); hset.add(20); System.out.println(“An initial list of elements”); System.out.println(hset); //Removing a specific element from the HashSet. hset.remove(10); System.out.println(“List of elements after removing 10”); System.out.println(hset); // Create another hash set object and add elements to the set. HashSet hset1=new HashSet(); hset1.add(10); hset1.add(25); hset.addAll(hset1); System.out.println(“List of Elements after adding elements from an existing collection”); System.out.println(hset); //Removing all the new elements from HashSet hset.removeAll(hset1); System.out.println(“List of Elements after removing elements from hset1”); System.out.println(hset); //Removing all the elements available in the set hset.clear(); System.out.println(“After invoking clear() method: “+hset); } }Output: An initial list of elements [20, 5, 10, 15] List of elements after removing 10 [20, 5, 15] List of Elements after adding elements from an existing collection [20, 5, 25, 10, 15] List of Elements after removing elements from hset1 [20, 5, 15] After invoking clear() method: [ ]

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 pCountry = new HashSet(); // Check if a HashSet is empty System.out.println(“Is popularCountries set empty? : ” + pCountry.isEmpty()); System.out.println(“Number of countries in the HashSet before adding: ” +pCountry.size()); pCountry.add(“INDIA”); pCountry.add(“USA”); pCountry.add(“UK”); pCountry.add(“FRANCE”); // Find the size of a HashSet System.out.println(“Number of countries in the HashSet after adding: ” + pCountry.size()); } }Output: Is popularCountries set empty? : true Number of countries in the HashSet before adding: 0 Number of countries in the HashSet after adding: 4

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 set = new HashSet(); // Check if a HashSet is empty System.out.println(“Is set empty? : ” + set.isEmpty()); System.out.println(“Number of elements in the HashSet before adding: ” +set.size()); set.add(“Dollar”); set.add(“Indian Rupee”); set.add(“Euro”); set.add(“Yen”); System.out.println(“List of Elements in the set”); System.out.println(set); // Find the size of a HashSet System.out.println(“Number of elements in the HashSet after adding: ” + set.size()); // Call contains() method to check an element exists in the set or not. if(set.contains(“Dollar”)){ System.out.println(“Does Element ‘Dollar’ exist in the set?”); System.out.println(“Yes, Element ‘Dollar’ exists in the set.”); } else{ System.out.println(“No, Element ‘Dollar’ does not exist in the set.”); } System.out.println(“Does Element ‘Dinar’ exist in the set?”); if(set.contains(“Dinar”)){ System.out.println(“Yes, Element ‘Dinar’ exists in the set. “); } else { System.out.println(“No, Element ‘Dinar’ does not exist in the set.”); } } } Output: Is set empty? : true Number of elements in the HashSet before adding: 0 List of Elements in the set [Yen, Dollar, Indian Rupee, Euro] Number of elements in the HashSet after adding: 4 Does Element ‘Dollar’ exist in the set? Yes, Element ‘Dollar’ exists in the set. Does Element ‘Dinar’ exist in the set? No, Element ‘Dinar’ does not exist in the 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 hset=new HashSet(); // Create objects of Student class and pass the parameters. Student s1=new Student(“John”, “RSVM”, 0012); Student s2=new Student(“Shubh”, “DPS”, 1234); Student s3=new Student(“Ricky”, “DAV”, 9876); // Adding elements to the HashSet and pass the reference variable s1, s2, s3. hset.add(s1); hset.add(s2); hset.add(s3); //Traversing HashSet for(Student s:hset){ System.out.println(s.name+” “+s.sName+” “+s.id); } } }

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.



This post first appeared on Scientech Easy, please read the originial post: here

Share the post

Java HashSet | Example & Programs

×

Subscribe to Scientech Easy

Get updates delivered right to your inbox!

Thank you for your subscription

×