🔹 What is a HashMap?
A HashMap in Java is a data structure that stores data in key-value pairs. It belongs to the java.util
package and implements the Map
interface.
✅ Key Characteristics:
- Stores data as (key, value) pairs.
- Keys must be unique, but values can be duplicated.
- Allows one null key and multiple null values.
- Not synchronized (not thread-safe by default).
- Offers constant-time performance for basic operations like
put()
andget()
.
🧠Internal Working:
- Internally uses a hash table.
- When you insert a key, its
hashCode()
is computed to determine the bucket location. - If two keys have the same hash, a collision occurs, and the map handles it using a linked list or tree (in newer Java versions).
🧪 Example:

🔹 What is a HashSet?
A HashSet is a collection that stores unique elements only. It implements the Set
interface and is also part of the java.util
package.
✅ Key Characteristics:
- No duplicate elements allowed.
- No key-value mapping—just values.
- Allows one null element.
- Unordered—does not maintain insertion order.
- Internally backed by a HashMap.
🧠Internal Working:
- Each element in the
HashSet
is stored as a key in an internalHashMap
, with a constant dummy value. - This is why it ensures uniqueness—because keys in a map must be unique.
🧪 Example:

🧠Summary:
Feature | HashMap | HashSet |
---|---|---|
Interface | Implements Map | Implements Set |
Stores | Key-value pairs | Unique values only |
Allows Duplicates | Keys: No, Values: Yes | No duplicates at all |
Null Handling | One null key, many null values | One null element |
Internal Use | Hash table | Backed by a HashMap |