About NewTechnoBuzz
Advertise
Contact Us

Friday, July 18, 2014

Difference between HashMap and HashSet in Java

Both HashMap and HashSet are part of collection framework which allows us to work with collection of objects. HashMap stores data as key-value pair while HashSet doesn't allow duplicate values. It is the most frequently asked question during any core java interview.

Collection Framework has their own interfaces and implementation classes. Basically collection is divided as Set Interface, List and Queue Interfaces. All this interfaces have their own property. Like, Set allows Collection of objects but forbids duplicate value, List allows duplicate along with indexing.
This article focuses on What are differences between HashSet and HashMap in terms of features, usage and performance. If you are in Java programming even for a year or so, you are likely to be familiar with What is HashSet in Java and What is HashMap in Java.

Despite being hash based collection HashSet and HashMap are different to each other because underlying interface are different. HashSet implements Set interface via extending AbstractSetclass and HashMap implements Map interface.

First we will look on What HashMap and Hashset is then will discuss about their similarity and differences between them.

What is HashSet in Java

HashSet is implementation of Set Interface which does not allow duplicate value. All the methods which are in Collection interface are also in Set Interface because Set extends Collection interface. HashSet uses hashing algorithm to store data, so it must override equals() and hashCode() method so that we can check for equality and no duplicate value are stored in HashSet. If we don't override the equals() and hashCode methods then they will take default implementation and we'll not be able to check that HashSet is containing duplicate value or not.

public boolean add(Object object) method is used to add element in a HashSet which returns false if it’s a duplicate value otherwise returns true if added successfully.
package com.gsms.test.console.app;
 
import java.util.HashSet;
import java.util.Iterator;
 
public class HashSetExample {
 
    public static void main(String args[]){
        HashSet<String> hsObj = new HashSet<String>();
        //add elements to HashSet
        hsObj.add("first");
        hsObj.add("second");
        hsObj.add("third");
        Iterator<String> itr = hsObj.iterator();
        while(itr.hasNext()){
            System.out.println(itr.next());
        }
    }
}

What is HashMap in Java

HashMap is a implementation of Map Interface, which stores data in key-value pair. Duplicate keys are not allowed in a map. Basically map Interface has two implementation classes: HashMap and TreeMap. We can store null key and null value in HashMap. HashMap is not synchronized, using Collections.synchronizedMap(Map m), we can synchronized HashMap.

public Object put(Object key,Object value) method is used to add element in HashMap.
package com.gsms.console.test;
 
import java.util.HashMap;
import java.util.Set;
 
public class HashMapTesting {
    public static void main(String args[]){
        HashMap<String, String> hmObj = new HashMap<String, String>();
        //add key-value pair to hashmap
        hmObj.put("first", "first");
        hmObj.put("second", "second");
        hmObj.put("third","third");
        System.out.println(hmObj);
        Set<String> keys = hmObj.keySet();
        for(String key: keys){
            System.out.println("Value of " + key + " is: " + hmObj.get(key));
        }
    }
}

Similarities between HashMap and HashSet in Java

Below are some of the similarities between both of them:
  • Both HashMap and HashSet are hash based collection in Java.
  • Both HashMap and HashSet are not synchronized and can not be shared between multiple threads.
  • Iterator returned by HashMap's keySet() and HashSet are fail-fast and throw ConcurrentModificationException if they detect any structural change in Collection.
  • Both HashMap and HashSet provided constant time performance for basic operations like put(), get() etc.
  • Both HashSet and HashMap allows null values.

Differences between HashSet and HashMap in Java

Following are some differences between HashMap and Hashset:
HashMap HashSet
HashMap is implementation of Map interface. HashSet is implementation of Set Interface.
HashMap stores data key-value pair. HashSet store only objects.
public Object put(Object key,Object value) method is used to add element in HashMap. public boolean add(Object object) method is used to add element is HashSet.
In HashMap, hash code value is calculated using key object. key object is used for calculating hashcode value which can be same for two objects so equals() and hashCode() methods must be overridden in order to check for equality.
But internally, HashSet uses HashMap to store objects. When add(String) method called then it calls HashMap put(key,value) method where
key=String object & value=new Object(Dummy). So, it maintains no duplicates because keys are nothing but Value Object.
HashMap is faster than HashSet because unique key is used to access object. HashSet is slower than Hashmap.
HashMap can allow one null key and multiple null values. HashSet allows only one null key.

That's all on difference between HashSet and HashMap in Java. In summary, HashSet and HashMap are two different type of Collection one being Set and other being Map.

Please feel to post your comments, suggestions and feedback to make this article better.

0 comments