Differentiate between HashSet and HashMap?
Feature | HashSet | HashMap |
Definition | HashSet is an implementation of the Set interface. It stores unique elements (no duplicates). | HashMap is an implementation of the Map interface. It maps keys to values (key-value pairs). |
Duplicates | HashSet does not allow duplicate elements. | HashMap allows duplicate values but not duplicate keys. |
Ordering | HashSet does not maintain any specific order of elements. | HashMap does not guarantee any specific order of key-value pairs. |
Null Values | HashSet allows a single null value. | HashMap allows a single null key and any number of null values. |
Implementation | HashSet uses a hash table for storage. | HashMap also uses a hash table for storage (key-value pairs). |
Example | java Set<String> names = new HashSet<>(); names.add(“Alice”); names.add(“Bob”); names.add(“Charlie”); System.out.println(names); | java Map<String, Integer> scores = new HashMap<>(); scores.put(“Alice”, 90); scores.put(“Bob”, 85); scores.put(“Charlie”, 78); System.out.println(scores); |
Table of Contents
In the examples above, HashSet stores unique names, while HashMap associates student names with their scores. Remember that HashSet is ideal for maintaining a collection of unique elements, while HashMap is useful for key-value mappings