HashSet Class In Java

HashSet Class In Java: HashSet Class is one of the classes of the Java Collection Framework. This extends the AbstractSet AbstractSet class, which implements the Set interface and internally uses HashTable for storage of the elements by using a mechanism called hashing.

In hashing, the informational content of a key is used to determine a unique value, called its hash code. The hash code is then used as the index at which the data associated with the key is stored. The transformation of the key into its hash code is performed automatically.

HashSet Class Declaration

public class HashSet<E> extends AbstractSet<E>
implements Set<E>, Cloneable, Serializable
{
//implementation
}

The insertion order has no guarantees; it allows null elements and duplicate values.

HashSet Class Important Features

  • It implements a Set interface.
  • HashSet Class internally used HashMap to store the elements
  • Duplicate values are not allowed.
  • Only one NULL element is allowed.
  • This makes no guarantees of the insertion order of the elements, which means the elements may not be the same as they are inserted, and the elements are stored based on their hash code.
  • This HashSet Class offers the constant time performance of different operations like (add, remove, contain, and size).
  • HashSet is not threaded safe, meaning the result is not deterministic if multiple threads act on the HashSet. But we can explicitly synchronize for a multi-thread environment with the help of Collections.synchronizedSet(new HashSet()).
  • It also implements Serializable and Cloneable interfaces.

Initial Capacity: Initial capacity means the number of elements allowed when a HashSet is created; the default value is 16. once the HashSet is full, the size will increase automatically.

Load Factor: Load Factor measures how full the HashSet should be before the capacity increases. So when the number of inserted elements reaches the hash table’s multiple load factor and size, the size becomes twice the number of buckets. the default load factor is 0.75

                 Number of stored elements in the table
load factor = -----------------------------------------
                        Size of the hash table

For Example, The default capacity for the HashSet is 16, and the load factor is 0.75 (16*0.75=12), so when the inserted element reaches 12, the size of the HashSet automatically increases.

HashSet Constructors

The HashSet has four types of constructors:

  • HashSet(): initializes a default HashSet instance with the initial default capacity (16) and load factor (0.75).
  • HashSet(int capacity): initializes a HashSet with a specified capacity and load factor (0.75).
  • HashSet(int capacity, float loadFactor): initializes HashSet with specified initial capacity and load factor.
  • HashSet(Collection c): initializes a HashSet with the same elements as the specified collection.

Examples Of HashSet

Write a program to find duplicate values using HashSet in Java.

package com.java.Softwaretestingblog;
import java.util.HashSet;
public class FindDuplicateValueUsingHashSet {
   public static void main(String[] args) {
      // TODO Auto-generated method stub
      HashSet<String> hs = new HashSet<String>();
      //add elements to HashSet
      hs.add("first");
      hs.add("second");
      hs.add("third");
      System.out.println(hs);
      System.out.println("Is HashSet empty? "+hs.isEmpty());
      hs.remove("third");
      System.out.println(hs);
      System.out.println("Size of the HashSet: "+hs.size());
      System.out.println("Does HashSet contains first element? "+hs.contains("first"));
   }
}

Output:

[third, first, second]
Is HashSet empty? false
[first, second]
Size of the HashSet: 2
Does HashSet contains first element? true

Remove Values From a HashSet: How do you remove values from a HashSet in Java?

package com.java.Softwaretestingblog;
import java.util.HashSet;
public class RemoveValuesFromHashSet {
   public static void main(String[] args) {
      // TODO Auto-generated method stub
      HashSet<String> hs = new HashSet<String>();
        //add elements to HashSet
        hs.add("first");
        hs.add("second");
        hs.add("third");
        System.out.println("My HashSet content:");
        System.out.println(hs);
        System.out.println("Clearing HashSet:");
        hs.clear();
        System.out.println("Content After clear:");
        System.out.println(hs);
   }
}

Output:

My HashSet content:
[third, first, second]
Clearing HashSet:
Content After clear:
[]

Add Subset Element In Java Program: How to Add Subset Element Into Set Of HashSet In Java?

package com.java.Softwaretestingblog;
import java.util.HashSet;
public class AddSubsetElementInHashSet {
   public static void main(String[] args) {
      // TODO Auto-generated method stub
      HashSet<String> hs = new HashSet<String>();
      //add elements to HashSet
      hs.add("first");
      hs.add("second");
      hs.add("third");
      System.out.println(hs);
      HashSet<String> subSet = new HashSet<String>();
      subSet.add("s1");
      subSet.add("s2");
      hs.addAll(subSet);
      System.out.println("HashSet content after adding another collection:");
      System.out.println(hs);
   }
}

Output:

[third, first, second]
HashSet content after adding another collection:
[third, first, s1, second, s2]

HashSet Values In Java Collection: Write A Program to Add & Retain HashSet Values in Java?

package com.java.Softwaretestingblog;
import java.util.HashSet;
public class Retain_HashSet_Values {
   public static void main(String[] args) {
      // TODO Auto-generated method stub
      HashSet<String> hs = new HashSet<String>();
      //add elements to HashSet
      hs.add("first");
      hs.add("second");
      hs.add("third");
      hs.add("apple");
      hs.add("rat");
      System.out.println(hs);
      HashSet<String> subSet = new HashSet<String>();
      subSet.add("rat");
      subSet.add("second");
      subSet.add("first");
      hs.retainAll(subSet);
      System.out.println("HashSet content:");
      System.out.println(hs);
   }
}

Output:

[apple, third, rat, first, second]
HashSet content:
[rat, first, second]

Print Duplicate Character Using HashSet In Java: How do you print duplicate characters using HashSet in Java with an example?

package com.java.Softwaretestingblog;
import java.util.HashSet;
public class PrintDuplicateCharacter {
   public static void main(String[] args) {
      // TODO Auto-generated method stub
      int [] dup={1,2,3,2};
      HashSet<Integer> uniq=new HashSet<Integer>();
      for(Integer x:dup)
      {
         if(uniq.add(x))
         {
            //System.out.println("Duplicate Entry is " +x);
            continue;
         }
         else
         {
            System.out.println("Duplicate Entry is " +x);
         }
      }
   }
}

Attempt to put every newly read character into a.Set<Character> If adding to the set returns false, add it to a set tracking all repeat characters.

Output:

Duplicate Entry is 2

Please comment if you find anything incorrect or want to share more information about the topic discussed above.

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

Leave a Comment