HashSet in java

In this tutorial we will learn Hashset class in java with examples.

This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element. This class is not synchronized. However it can be synchronized explicitly like this: Set s = Collections.synchronizedSet(new HashSet(...));


  1. HashSet doesn’t maintain any order, the elements would be returned in any random order.
  2. HashSet doesn’t allow duplicates. If you try to add a duplicate element in HashSet, the old value would be overwritten.
  3. HashSet allows null values however if you insert more than one nulls it would still return only one null value.
  4. HashSet is non-synchronized.
  5. The iterator returned by this class is fail-fast which means iterator would throw ConcurrentModificationException if HashSet has been modified after creation of iterator, by any means except iterator’s own remove method.

See Example:


import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

public class Example1 {
 public static void main(String args[]) {
                       // HashSet declaration
HashSet<String> hashset = getHashSet()
 }
public static   HashSet<String> getHashSet(){
   // HashSet declaration
      HashSet<String> hashset  =  new HashSet<String>();

      // Adding elements to the HashSet
      hashset.add("Item4");
      hashset.add("Item2");
      hashset.add("Item6");
      hashset.add("Item1");
      hashset.add("Item3");
      hashset.add("Item5");
      //Addition of duplicate elements
      hashset.add("Item2");
      hashset.add("Item4");
      //Addition of null values
      hashset.add(null);
      hashset.add(null);
   
      System.out.println("---Loop for---");
     
      for (String temp : hashset) {
          System.out.println(temp);
       }
      return hashset;
}
}
//result : 
---Loop for---
null
Item1
Item2
Item5
Item6
Item3

in this result we saw in Hashset no duplicate values and not order values



EmoticonEmoticon