HashSet in Java

  • The HashSet class extends AbstractSet and implements set interface.
  • A Set is collection of unique elements.
  • The HashSet class supports sets using a hash internally for storage by using mechanism called hashing.
  • The HashSet doesn’t allow duplicate element.
  • If you try to add a duplicate element in add method of set then it will return false.
  • In hashing, The informational content of a key is used to determine a unique value, called hash code.
  • The HashSet provides basic operation such as add(), contains(), remove() and size() method.
  • HashSet is not synchronized. If more than one thread wants to access it at the same time then it must be synchronized externally.
The following table demonstrates the constructors of HashSet and corresponding methods.

Constructor
Meaning
HashSet()
Constructs empty HashSet Object.
HashSet(Collection c)
Constructs a new set containing the elements of the given collection.
HashSet(int Capacity)
Constructs empty set with given initial capacity.
HashSet(int Capacity, float loadfactor)
Constructs empty set with given initial capacity and the given load factor.

The following program shows a simple use of HashSet. 

Example:

/**
From SimpleHashSet.java
*/

import java.util.HashSet;
/**
 *
 * @author JavaHotSpot
 */

public class SimpleHashSet
{
  public static void main(String args[])
  {
      HashSet<String> set = new HashSet<String>();
      set.add("Book1");
      set.add("Book2");
      set.add("Book3");
      set.add("Book4");
      set.add("Book5");
      set.add("Book6");
      System.out.println("The HashSet elements are"+"\n"+set);
  }
}

Output:
The HashSet elements are
[Book2, Book1, Book4, Book3, Book6, Book5]

Note:
In HashSet, you can’t guarantee the order in which element are strored internally, In fact, when you print the hashset you can see that all the elements are stored in randomly sometimes exactly reverse order.

The following program shows a simple use of HashSet with use of Iterator Interaface. 

Example:

/**
From HashSerwithIterator.java
*/

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

/**
 *
 * @author JavaHotSpot
 */

public class HashSerwithIterator
{
  public static void main(String args[])
  {
      String ss;
      HashSet<String> set = new HashSet<String>();
      set.add("Book0");
      set.add("Book1");
      set.add("Book2");
      set.add("Book3");
      set.add("Book4");
      set.add("Book5");
      set.add("Book6");
      System.out.println("The HashSet elements are");
      Iterator it = set.iterator();
      while(it.hasNext())
      {
          ss=(String)it.next();
          System.out.println(ss);
      }
  }
}

Output:
The HashSet elements are
Book0
Book2
Book1
Book4
Book3
Book6
Book5