BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

HashSet in Java With Examples

Last Updated: September 23, 2022 by Chaitanya Singh | Filed Under: java

This class implements the Set interface, backed by a hash table (actually a HashMap instance). It does not guarantee the iteration order of the set. This means that the iteration order of Java HashSet elements doesn’t remain constant. This class permits the null element.

Points to Note about HashSet:

  1. HashSet internally uses Hashtable data structure.
  2. HashSet doesn’t maintain any order, the elements would be returned in any random order.
  3. HashSet doesn’t allow duplicates. If you try to add a duplicate element in HashSet, the old value would be overwritten.
  4. HashSet allows null values, however if you insert more than one nulls, it would override the previous null value.
  5. HashSet is non-synchronized. However it can be synchronized explicitly like this: Set s = Collections.synchronizedSet(new HashSet(...));
  6. 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.

A Simple Example of HashSet in Java

Let’s see a simple HashSet example, where we are adding few string elements to HashSet and then iterating the HashSet to print the elements.

import java.util.HashSet;
public class JavaExample {
  public static void main(String args[]) {
    // HashSet declaration
    HashSet<String> hSet = new HashSet<>();

    // Adding elements to the HashSet
    hSet.add("Cricket");
    hSet.add("Hockey");
    hSet.add("Basketball");

    System.out.println("HashSet Elements: ");
    // Iterating HashSet
    for(String s: hSet){
      System.out.println(s);
    }
  }
}

Output:

HashSet in Java Example

HashSet class Hierarchy

HashSet class extends AbstractSet class. The AbstractSet class implements Set interface, which extends Collection interface. This hierarchy can be represented as follows:

HashSet -> AbstractSet -> Set -> Collection -> Iterable

HashSet Declaration

HashSet class belongs to java.util package. The declaration of HashSet in Java is:

public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, Serializable

Initial Capacity and Load Factor:

Initial capacity represents the initial data buckets allocated to HashSet, this automatically increases when HashSet gets full.

Load factor measures the load of HashSet, it represents how much the HashSet is full. A load factor of .60 means that when HashSet is 60% full, the capacity of HashSet is automatically increased.

                         Number of element in HashSet
Load Factor Of HashSet = ----------------------------
                         Size of the HashSet

Constructors of Java HashSet Class

ConstructorDescription
HashSet()It builds an empty HashSet with initial capacity of 16 and load factor of .75.
Example: HashSet<String> hSet = HashSet<>();
HashSet(int initialCapacity)It builds an empty HashSet with the specified initial capacity. The default load factor remains .75.
HashSet(int initialCapacity, float loadFactor)It builds an empty HashSet with the specified initial capacity and load factor.
HashSet(Collection)This doesn’t create an empty HashSet. It creates the HashSet with the elements copied from the passed Collection.

Java HashSet Examples

Let’s see few examples of HashSet in Java.

1. Adding duplicate elements

HashSet overrides duplicate values.

import java.util.HashSet;
public class HashSetExample {
   public static void main(String args[]) {
      // HashSet declaration
      HashSet<String> hset = 
               new HashSet<String>();

      // Adding elements to the HashSet
      hset.add("Apple");
      hset.add("Mango");
      hset.add("Grapes");
      hset.add("Orange");
      hset.add("Fig");
      //Addition of duplicate elements
      hset.add("Apple");
      hset.add("Mango");
      //Addition of null values
      hset.add(null);
      hset.add(null);

      //Displaying HashSet elements
      System.out.println(hset);
    }
}

Output:

[null, Mango, Grapes, Apple, Orange, Fig]

As you can see there all the duplicate values are not present in the output including the duplicate null value.

2. Removing elements

import java.util.HashSet;
public class JavaExample {
  public static void main(String args[]) {
    // HashSet declaration
    HashSet<String> hSet = new HashSet<>();

    // Adding elements to the HashSet
    hSet.add("AA");
    hSet.add("BB");
    hSet.add("CC");
    hSet.add("DD");
    hSet.add("EE");

    //removing elements
    hSet.remove("EE");
    hSet.remove("CC");

    System.out.println("HashSet Elements: ");
    // Iterating HashSet
    for(String s: hSet){
      System.out.println(s);
    }
  }
}

Output:

HashSet Elements: 
AA
BB
DD

3. Adding elements from other Collection

Here, we are adding ArrayList elements to HashSet

import java.util.*;
public class JavaExample {
  public static void main(String args[]) {
    //ArrayList declaration and and adding elements
    ArrayList<String> arrList=new ArrayList<>();
    arrList.add("AA");
    arrList.add("BB");
    arrList.add("CC");

    //copying ArrayList elements to HashSet
    HashSet<String> hSet=new HashSet(arrList);
    //adding another element to HashSet after copy
    hSet.add("DD");

    System.out.println("HashSet elements: ");
    Iterator<String> it= hSet.iterator();
    while(it.hasNext())
    {
      System.out.println(it.next());
    }
  }
}

Output:

HashSet elements: 
AA
BB
CC
DD

HashSet Methods:

  1. boolean add(Element  e): It adds the element e to the list.
  2. void clear(): It removes all the elements from the list.
  3. Object clone(): This method returns a shallow copy of the HashSet.
  4. boolean contains(Object o): It checks whether the specified Object o is present in the list or not. If the object has been found it returns true else false.
  5. boolean isEmpty(): Returns true if there is no element present in the Set.
  6. int size(): It gives the number of elements of a Set.
  7. boolean(Object o): It removes the specified Object o from the Set.

More HashSet Guides:

  • Delete all elements from HashSet
  • How to iterate through a HashSet
  • Convert a HashSet to an array
  • Convert a HashSet to a TreeSet
  • Convert HashSet to a List/ArrayList
  • HashSet vs HashMap
  • HashSet vs TreeSet
❮ PreviousNext ❯

Top Related Articles:

  1. Java StringBuffer toString()
  2. Java StringBuilder append() Method
  3. Difference between HashSet and TreeSet
  4. How to convert a HashSet to a TreeSet
  5. Difference between String and StringBuffer

Tags: Collections, Java-HashSet

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Comments

  1. Mahesh says

    September 25, 2015 at 7:03 AM

    What is the difference between HashSet & ArrayList.

    Reply
    • Umesh says

      February 12, 2016 at 9:28 AM

      Array list is ordered collection and allowed duplicates where HashSet is not

      Reply
    • Abhay Kumar Dash says

      August 18, 2016 at 8:42 PM

      In Array List Dont follow default Sorting mechanism but In case Of Hash Set its possible and Insertion is not preserved in Hash set
      So the Collection Gives Facility for default sorting by using utility class ‘Collections’

      Reply
  2. Torben says

    November 14, 2015 at 9:01 PM

    quick and easy tutorial for java hashsets. thanks!

    Reply
  3. Marcos Lerin says

    February 9, 2016 at 9:11 PM

    I think this point is not correct:
    2.-HashSet doesn’t allow duplicates. If you try to add a duplicate element in HashSet, the old value would be overwritten.

    The Java docs mention: If this set already contains the element, the call leaves the set unchanged and returns false.

    Reply
  4. RAVI PRAKASH says

    February 18, 2016 at 9:22 AM

    Hash set can contains null value whereas array list cannot

    Reply
  5. ARNOLD says

    June 1, 2016 at 8:44 AM

    hello
    thanks for your site
    i have a Question
    how can
    Writing program with Hashset that show me
    Repetitive words ???

    Reply
  6. manish gour says

    June 3, 2016 at 1:07 PM

    This tutorial is superb, I like it.

    and It think by – “if HashSet has been modified after creation of iterator”
    You mean this:

    HashSet hs = new HashSet();

    Song s1 = new Song(“zzz”, “zaheer”, “23”, “343”);
    Song s2 = new Song(“xx”, “mosin”, “23”, “343”);

    hs.add(s1);
    hs.add(s2);

    Iterator itr = hs.iterator();

    Song s6 = new Song(“ooo”, “yakoob”, “23”, “343”);
    hs.add(s6);

    while (itr.hasNext()) {
    System.out.println(itr.next());
    }

    Reply
  7. shardul says

    November 24, 2016 at 10:29 AM

    ==================Hash List===================
    [null, Apple, Grapes, Fig, Mango, Orange]
    hi, I tried your code but it gets the result in sorted format.

    Reply
  8. Naja says

    August 11, 2017 at 6:55 AM

    can equal objects be added to hashset ? if yes then why it is not considered as duplicate ?

    Reply
  9. amin says

    December 15, 2017 at 6:37 AM

    thank you for the tutorial
    but the fact that ” If you try to add a duplicate element in HashSet, the old value would be overwritten.” is not true.
    according to what it says on oracle website in this link (https://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html), it’s the other way around (i.e. if element_to_be_added is a duplicate, it won’t be added at all):

    public boolean add(E e)

    Adds the specified element to this set if it is not already present. More formally, adds the specified element e to this set if this set contains no element e2 such that (e==null ? e2==null : e.equals(e2)). If this set already contains the element, the call leaves the set unchanged and returns false.

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap