HashSet in java

Let’s learn hashset in java.

HashSet java

  • underlying data structure for hashset is Hash table.
  • HashSet implements Set interface.
  • Hashset do not allow duplicate elements. If any duplicate object is added, then add() method returns “false” without adding any duplicate object.
  • Object are inserted based on hash code.
  • Hashset insertion order is not preserved.
  • In hashset all objects will be inserted based on hashcode of objects.
  • In hashset heterogeneous elements are allowed.
  • Hashset allow “null” value.
  • Hashset implements Serializable and Cloneable interface.
  • In hashset, searching objects is easier. Because objects are stored based on hashcode.
  • HashSet do not implement RandomAccess interface.

Let’s see simple example on hashset,

import java.util.HashSet;

public class HashSetDemo 
{
   public static void main(String[] args) 
   {
      HashSet hs = new HashSet();
      // adding heterogeneous elements
      hs.add("Dhoni");
      hs.add("Sachin");
      hs.add("Virat");
      hs.add("Ajinkya");
      hs.add(null);
      hs.add(100);
      // duplicate elements not allowed
      System.out.println(hs.add("Ajinkya"));
      // insertion order is not preserved
      System.out.println(hs);
   }
}



Output:

false
[null, 100, Ajinkya, Dhoni, Sachin, Virat]


Initial capacity : is initial number of buckets that a Hashset object can hold.

Also read – treeset in java

Load factor/ fill ratio: is a measure to calculate after how much load a new hashset object is created.

                                no. of elements in the table
load factor   =    ————————————————-
                                       size of hash table

NOTE : best load factor would be 0.75 with respect to time and space complexity, according to java.

hashset in java

Here you can see hierarchy of hashset class. Hashset class extends abstractset class. AbstractSet class implements set interface.

And set interface extends collection interface. Collection interface extends iterable interface.


Also read – treemap in java


Hashset methods

MethodsDescription
boolean add ( E e )adds the specified element to this set if it is not already present
void clear ( )removes all of the elements from this set.
Object clone ( )returns a shallow copy of this HashSet instance: the elements themselves are not cloned.
boolean contains ( Object o )returns true if this set contains the specified element.
boolean isEmpty ( )method used to check whether the set is empty or not. Returns true if this set contains no elements and false for non-empty condition.
Iterator iterator()returns an iterator over the elements in this set.
boolean remove ( Object o )removes the specified element from this set if it is present.
int size ( )returns the number of elements in this set ( its cardinality ).

Constructors in hashset

  • HashSet h = new HashSet();

This constructor creates an empty hashset object with default initial capacity 16 and default fill ratio or load factor 0.75


  • HashSet h = new HashSet(int initialCapacity);

this constructor creates hashset object with specified initialCapacity with load factor 0.75. Nothing but customized initial capacity and default load factor.


  • HashSet h = new HashSet(int initialCapacity, float loadFactor);

Here we can customize load factor.


  • HashSet h = new HashSet(Collection C);

If you want Interconversion between Collection object then use this constructor.


Let’s see hashset implementation in java,

import java.util.HashSet;
import java.util.Iterator;

public class HashsetExample
{
   public static void main(String[] args)
   {
      // HashSet declaration
      HashSet<String> hs = new HashSet<String>();
      // add to hashset java
      hs.add("orange");
      hs.add("mango");
      hs.add("strawberry");
      // now adding duplicate values to HashSet
      hs.add("orange");

      // display the HashSet 
      System.out.println(hs); 
      System.out.println("HashSet contains orange or not : " + hs.contains("orange")); 

      // hashset remove java 
      hs.remove("mango"); 
      System.out.println("HashSet after removing - mango : " + hs); 

      // iterate through hashset 
      System.out.println("Iterating over list : "); 
      Iterator<String> iterate = hs.iterator(); 
      while(iterate.hasNext())
      {
         System.out.println(iterate.next());
      }
   }
}



Output:

[orange, strawberry, mango]

HashSet contains orange or not : true
HashSet after removing – mango : [orange, strawberry]
Iterating over list :
orange
strawberry


Reference – Oracle help centre