Friday, December 27, 2013

Difference between HashSet and HashMap in Java

HashSet and HashMap in Java
HashSet vs HashMap is a classical Java Collection interview question which 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, these two are most popular collection classes. 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 HashMapimplements Map interface. Before seeing differences between let's see what is common between HashSet and HashMap in Java:


Similarities on HashMap and HashSet in Java
Here are some of the common stuff between both of them:

1) Both HashMap and HashSet are hash based collection in Java.
2) Both HashMap and HashSet are not synchronized and can not be shared between multiple threads.
3) Iterator returned by HashMap's keySet() and HashSet are fail-fast and they throwConcurrentModificationException if they detect any structural change in Collection.

4) Both HashMap and HashSet provided constant time performance for basic operations like put(), get() etc.
5) Both HashSet and HashMap allows null values.

Differences between HashSet and HashMap in Java

Difference between HashSet vs HashMap in JavaAfter seeing similarities on HashMap and HashSet, now let's see some difference between them :

1) First and most significant difference between HashMap and HashSet is that HashMap is an implementation of Map interface while HashSet is an implementation of Set interface, which means HashMap is a key value based data-structure and HashSet guarantees uniqueness by not allowing duplicates.In reality HashSet is a wrapper around HashMap in Java, if you look at the code of add(E e) method of HashSet.java you will see following code :

public boolean add(E e) {
        return map.put(e, PRESENT)==null;
}

where its putting  Object into map as key and value is an final object PRESENT which is dummy.

2) Second difference between HashMap and HashSet is that , we use add() method to put elements into Set but we use put() method to insert key and value into HashMap in Java.

3) HashSet allows only one null key, but HashMap can allow one null key + multiple null values.

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.


Other Java Collection tutorials:

No comments: