Difference between HashSet and HashMap? Difference between HashSet and HashMap? java java

Difference between HashSet and HashMap?


HashSet is a set, e.g. {1,2,3,4,5}

HashMap is a key -> value (key to value) map, e.g. {a -> 1, b -> 2, c -> 2, d -> 1}

Notice in my example above that in the HashMap there must not be duplicate keys, but it may have duplicate values.

In the HashSet, there must be no duplicate elements.


They are entirely different constructs. A HashMap is an implementation of Map. A Map maps keys to values. The key look up occurs using the hash.

On the other hand, a HashSet is an implementation of Set. A Set is designed to match the mathematical model of a set. A HashSet does use a HashMap to back its implementation, as you noted. However, it implements an entirely different interface.

When you are looking for what will be the best Collection for your purposes, this Tutorial is a good starting place. If you truly want to know what's going on, there's a book for that, too.


HashSet

  1. HashSet class implements the Set interface
  2. In HashSet, we store objects(elements or values)e.g. If we have a HashSet of string elements then it could depict aset of HashSet elements: {“Hello”, “Hi”, “Bye”, “Run”}
  3. HashSet does not allow duplicate elements that mean youcan not store duplicate values in HashSet.
  4. HashSet permits to have a single null value.
  5. HashSet is not synchronized which means they are not suitable for thread-safe operations until unless synchronized explicitly.[similarity]

                          add      contains next     notesHashSet               O(1)     O(1)     O(h/n)   h is the table 

HashMap

  1. HashMap class implements the Map interface
  2. HashMap isused for storing key & value pairs. In short, it maintains themapping of key & value (The HashMap class is roughly equivalent toHashtable, except that it is unsynchronized and permits nulls.) Thisis how you could represent HashMap elements if it has integer keyand value of String type: e.g. {1->”Hello”, 2->”Hi”, 3->”Bye”,4->”Run”}
  3. HashMap does not allow duplicate keys however it allows having duplicate values.
  4. HashMap permits single null key and any number of null values.
  5. HashMap is not synchronized which means they are not suitable for thread-safe operations until unless synchronized explicitly.[similarity]

                           get      containsKey next     Notes HashMap               O(1)     O(1)        O(h/n)   h is the table 

Please refer this article to find more information.