Difference Between HashMap and HashSet in Java

Connect with

java-logoHashMap and HashSet is one of the most frequently asked interview question during any level of core java interview. Usually, Collection framework and multi-threading interview questions are mostly on demand for core java interview question.

Both HshMap and HashSet are integral part of Collection framework in java. These are most frequently used collection classes, it means , HashMap from Map , HashSet from Set and ArrayList from List in java.

Let us go through one by one both of these i.e. HashMap and HashSet and afterward will go for Differences between them i.e. HashSet and HashMap

HashMap in Java?

HashMap is an implementation of Map Interface, store key and value , it means, maps a key to its value. Basically, map Interface has three implementation classes HashMap, LinkedHashMap and TreeMap. It works on hasing technique, so complexty of getting element is O(1).

Key Points of HashMap are:

  • Duplicate keys are not allowed in a map i.e. HashMap but duplicate values are allowed.
  • HashMap not maintain insertion order.
  • HashMap allows null values and one null keys.
  • HashMap is not synchronized, but collection framework provide way to make them synchronized using Collections.synchronizedMap().
  • public Object put(Object Key,Object value) method is used to add an element in the map.

HashSet in Java?

HashSet is implementation of Set Interface which does not allow duplicate value. basic fundamental is Set does not allow null, duplicate element and not maintain insertion order , maintain sorting order.

Key Points about HashSet are:

  • Does not allow null
  • it maintain sorting order not insertion order
  • objects which are going to be stored in HashSet must override equals() and hashCode() method, so that , can check for equality and no duplicate value will stored in set.
  • add(Object o) returns true if unique value added , if duplicate then returns false.

Difference between HashSet and HashMap in Java

differences between HashMap and HashSet are as::

[table “” not found /]

Please let me know by writing comment on this post, if you want to add any other difference between HashSet and HashMap in Java or any suggestions.

Connect with

Leave a Reply

Your email address will not be published. Required fields are marked *