Tutorials

Java Collection Framework


Java Hashset


HashSet implements Set interface and extends AbstractSet class.

It is part of java.util package.

 

Declaration of HashSet class


public class HashSet extends AbstractSet implements Set, Cloneable, Serializable  

 

Key feature of HashSet

  • HashSet contain unique elements only. If you add duplicate in it, previous value will be overwritten (see example).
  • HashSet allows one null value only.
  • HashSet doesn’t maintain insertion order so when you retrieve elements from it they may be returned in random order. If you want to get element in order of insertion, use LinkedHashSet.
  • HashSet is non-Synchronized.
  • HashSet internally uses HashTable to store the elements.

Create HashSet in java

Now let’s look at the ways in which we can create HashSet in java.

  • HashSet hSet = new HashSet();
  • HashSet hSet = new HashSet (Collection c);
  • HashSet hSet = new HashSet (int initialCapacity);
  • HashSet hSet = new HashSet (int initialCapacity, float LoadFactor);

Simple example on HashSet


package tihHashSet;

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

public class ItrTraversal {

       public static void main(String[] args) {

         //create Array List
         HashSet javaRadarSet = new HashSet();

         //Add elements to ArrayList
         javaRadarSet.add("Java");
         javaRadarSet.add("Java"); //duplicate value
         javaRadarSet.add("Spring");
         javaRadarSet.add("Hibernate");
         javaRadarSet.add("EJB");

         //creating iterator to traverse over javaRadarList
         Iterator setIterator = javaRadarSet.iterator();

         while(setIterator.hasNext()){
             System.out.println(setIterator.next());

         }

    }

}

OUTPUT

Java
Hibernate
Spring
EJB
 

Now let’s look at different ways in which you can use HashSet that we created.

 

HashSet operations

  • Sort the elements in HashSet (if sorting is required, better use TreeSet)
  • Search element in HashSet
  • Remove element from HashSet
  • Remove all elements from the HashSet
  • Remove element from a particular index in HashSet

 

Traverse LinkedList

  • Traverse HashSet using Iterator
  • Traverse HashSet using Enumeration

You cannot traverse Set with ListIterator

 



Please Share this page
Views : 102
Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!