Java

Difference and Similarities between HashSet and HashMap

Following highlights the difference and Similarities between HashSet and HashMap

Differences between HashSet and HashMap

  • HashSet: HashSet class implements the Set interface
    HashMap: HashMap class implements the Map interface
  • HashSet: In HashSet we store objects(elements or values) ex. If we have a HashSet of string elements then it could depict a set of HashSet elements: {“Hi”, “you”, “there”}
    HashMap: 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: ex. {1->”Hi”, 2->”You”, 3->”there”}
  • HashSet: HashSet does not allow duplicate elements that means you can not store duplicate values in HashSet.
    HashMap: HashMap does not allow duplicate keys however it allows to have duplicate values.
  • HashSet: HashSet permits to have a single null value.
    HashMap: HashMap permits single null key and any number of null values.

Similarities 

  • Both HashMap and HashSet are not synchronized which means they are not suitable for thread-safe operations unitl unless synchronized explicitly.
  • Both of these classes do not guarantee that the order of their elements will remain constant over time.
  • 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.
  • They both provide constant time performance for basic operations such as adding, removing element etc.
HashSet and HashMap

Leave a Reply

Your email address will not be published.