HashSet Vs HashMap in Java

As the names imply, a HashMap is an associative Map and HashSet is just a Set . But they are entirely different constructs. A HashMap is an implementation of Map interface. A Map interface maps keys to values. The key look up occurs using the hash. On the other hand, a HashSet is an implementation of Set interface. 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.

HashMap is used to store key-value pairs using put method Example: hm.put(key, value); while HashSet is used to store only unique objects using add method Example: hs.add(object);.

HashMap doesn't allow duplicate keys but values can be duplicated while HashSet doesn't allow duplicate objects

HashMap allows maximum of one null key but any number of NULL values allowed while HashSet allows maximum of one null object to be added

HashSet internally uses HashMap. So, there shouldn't be any performance difference whatsoever if you use them for the same purpose.

HashSet Implementation


HashMap Implementation

How to create an Excel Document Programmatically

Output (C) 2022    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.
SiteMap  | Terms  | About