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

Difference between HashSet and HashMap

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

In this article we are gonna discuss the differences between HashSet and HashMap classes.

HashSet vs HashMap

Differences:

HashSet HashMap
HashSet class implements the Set interface HashMap class implements the Map interface
In HashSet we store objects(elements or values) e.g. If we have a HashSet of string elements then it could depict a set of HashSet elements: {“Hello”, “Hi”, “Bye”, “Run”} HashMap is used for storing key & value pairs. In short it maintains the mapping of key & value (The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.) This is how you could represent HashMap elements if it has integer key and value of String type: e.g. {1->”Hello”, 2->”Hi”, 3->”Bye”, 4->”Run”}
HashSet does not allow duplicate elements that means you can not store duplicate values in HashSet. HashMap does not allow duplicate keys however it allows to have duplicate values.
HashSet permits to have a single null value. HashMap permits single null key and any number of null values.

Similarities:
1) Both HashMap and HashSet are not synchronized which means they are not suitable for thread-safe operations unitl unless synchronized explicitly. This is how you can synchronize them explicitly:
HashSet:

Set s = Collections.synchronizedSet(new HashSet(...));

HashMap:

 Map m = Collections.synchronizedMap(new HashMap(...));

2) Both of these classes do not guarantee that the order of their elements will remain constant over time.

3) If you look at the source code of HashSet then you may find that it is backed up by a HashMap. So basically it internally uses a HashMap for all of its operations.

4) They both provide constant time performance for basic operations such as adding, removing element etc.

HashSet example

import java.util.HashSet;
class HashSetDemo{ 
  public static void main(String[] args) {
     // Create a HashSet
     HashSet<String> hset = new HashSet<String>();
 
     //add elements to HashSet
     hset.add("AA");
     hset.add("BB");
     hset.add("CC");
     hset.add("DD");
 
     // Displaying HashSet elements
     System.out.println("HashSet contains: ");
     for(String temp : hset){
        System.out.println(temp);
     }
  }
}

Output:

HashSet contains: 
AA
BB
CC
DD

HashMap example

import java.util.HashMap;
class HashMapDemo{ 
  public static void main(String[] args) {
     // Create a HashMap
     HashMap<Integer, String> hmap = new HashMap<Integer, String>();
 
     //add elements to HashMap
     hmap.put(1, "AA");
     hmap.put(2, "BB");
     hmap.put(3, "CC");
     hmap.put(4, "DD");
 
     // Displaying HashMap elements
     System.out.println("HashMap contains: "+hmap);
  }
}

Output:

HashMap contains: {1=AA, 2=BB, 3=CC, 4=DD}

References:

HashSet javadoc
HashMap javadoc

Top Related Articles:

  1. How to loop LinkedList in Java
  2. LinkedHashMap in Java
  3. How to convert a HashSet to a TreeSet
  4. How to synchronize HashMap in Java with example
  5. Difference between String and StringBuffer

Tags: Collections, Java-HashMap, 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. Prateek Mishra says

    August 11, 2015 at 10:06 AM

    Excellent Description. Wonderful Website with Examples.

    Reply
  2. srikanth says

    January 23, 2017 at 12:47 PM

    How HashSet internally uses the HashMap?

    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