JavaGian java tutorial and java interview question and answer

JavaGian , Free Online Tutorials, JavaGian provides tutorials and interview questions of all technology like java tutorial, android, java frameworks, javascript, ajax, core java, sql, python, php, c language etc. for beginners and professionals.

Difference between HashSet and HashMap in Java

Similarities on HashMap and HashSet in Java

1) Both HashMap and HashSet are a 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 throw ConcurrentModificationException 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


1) The 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 it's putting  Object into a map as key and value is a final object PRESENT which is a dummy.

2) The 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.

.