What is HashMap in Java?
A HashMap in Java is a part of the java.util package that implements the Map interface. It is a key-value pair-based data structure that uses a hashing mechanism to store and retrieve elements efficiently.
Key Features of HashMap
- Allows null values but only one null key.
- No duplicate keys are allowed, but values can be duplicated.
- Unordered collection – does not maintain the insertion order.
- Not thread-safe – must be synchronized externally if used in multithreading.
- Uses hashing to store keys in buckets, improving retrieval speed.
How HashMap Works Internally?
- Hashing Mechanism:
- The
hashCode()method determines the bucket index. - It uses (hashCode % capacity) to store the key-value pair.
- The
- Collision Handling:
- If two keys generate the same bucket index, chaining (Linked List in Java 7, Balanced Tree in Java 8) is used to store multiple entries.
Example of HashMap
Output:
Difference Between HashMap and HashTable
| Feature | HashMap | HashTable |
|---|---|---|
| Thread-Safety | Not synchronized (Not thread-safe) | Synchronized (Thread-safe) |
| Performance | Faster as it is not synchronized | Slower due to synchronization |
| Null Key/Values | Allows one null key and multiple null values | Does not allow null keys or values |
| Iteration Order | No guarantee of iteration order | No guarantee of iteration order |
| Fail-Fast | Yes (modifies structure while iterating throws ConcurrentModificationException) | No fail-fast behavior |
Example: HashTable
Common Interview Questions & Answers on HashMap
1. What is HashMap and how does it work?
Answer: HashMap is a part of java.util package that implements Map interface, storing key-value pairs using a hashing mechanism. It uses the hashCode() method to compute the index of the key-value pair and stores them in buckets.
2. How does HashMap handle collisions?
Answer: HashMap handles collisions using chaining:
- Java 7 and earlier: Uses a Linked List in each bucket.
- Java 8 and later: Uses Balanced Tree (Red-Black Tree) when bucket size exceeds 8 elements to optimize performance.
3. Why is HashMap not thread-safe?
Answer: HashMap is not synchronized, meaning multiple threads accessing and modifying it simultaneously can lead to race conditions and data inconsistencies.
Solution?
Use:
- ConcurrentHashMap for a thread-safe version.
- Collections.synchronizedMap(new HashMap<>()) for manual synchronization.
4. What happens if two keys have the same hashCode?
Answer: If two keys have the same hashCode, they are placed in the same bucket. The second key is stored in a linked list (Java 7) or Red-Black Tree (Java 8) at that bucket location.
5. What is the default initial capacity and load factor of HashMap?
Answer:
- Default capacity =
16 - Default load factor =
0.75(Resize happens when the HashMap is 75% full)
6. How does resizing work in HashMap?
Answer: When the number of elements exceeds (capacity × load factor), the capacity is doubled, and elements are rehashed (recomputed and stored in new locations).
7. Difference Between HashMap, LinkedHashMap, and TreeMap?
| Feature | HashMap | LinkedHashMap | TreeMap |
|---|---|---|---|
| Ordering | No order | Maintains insertion order | Sorted by keys (Natural Ordering) |
| Performance | O(1) | O(1) | O(log n) |
| Null Key | Allowed | Allowed | Not allowed |
8. What is fail-fast behavior in HashMap?
Answer: If a HashMap is modified structurally while iterating using an Iterator, it throws a ConcurrentModificationException.
Example
9. How do you make HashMap thread-safe?
Answer: Use:
Collections.synchronizedMap(new HashMap<>())ConcurrentHashMap(recommended)
10. Why is HashMap faster than TreeMap?
Answer: HashMap provides O(1) time complexity for get/put operations, whereas TreeMap uses O(log n) as it uses a Red-Black tree for sorting.
Conclusion
- HashMap is a widely used data structure for fast key-value retrieval.
- Handles collisions using chaining (Linked List or Tree).
- Not synchronized, use ConcurrentHashMap for thread safety.
- Resizing & rehashing happens automatically when it reaches the load factor.
Comments
Post a Comment