Loading

Q1. What is a HashMap in Java, and how does it work internally?

HashMap is a Map implementation that uses hashing to store key-value pairs. Internally, it uses an array of buckets and stores entries as linked lists (or trees in case of high collisions in Java 8+). The hashcode of a key determines the bucket index.






Q2. Can a HashMap have null keys and null values?

Yes, HashMap allows one null key and multiple null values.






Q3. What is the time complexity of HashMap operations?

The average time complexity of put() and get() operations is O(1). In the worst case (hash collisions), it can degrade to O(log n) (since Java 8 uses tree-based buckets).







Q4.  How does HashMap differ from Hashtable?
  • HashMap is not synchronized (faster, not thread-safe).
  • Hashtable is synchronized (thread-safe but slower).
  • HashMap allows one null key, Hashtable does not.





Q5. How does HashMap handle collisions?

HashMap resolves collisions using chaining. Initially, collisions are stored as linked lists in a bucket, but from Java 8 onwards, when the list size exceeds a threshold, it is converted into a balanced tree for better performance.






Q1. What is a HashMap in Java, and how does it work internally?

HashMap is a Map implementation that uses hashing to store key-value pairs. Internally, it uses an array of buckets and stores entries as linked lists (or trees in case of high collisions in Java 8+). The hashcode of a key determines the bucket index.






Q2. Can a HashMap have null keys and null values?

Yes, HashMap allows one null key and multiple null values.






Q3. What is the time complexity of HashMap operations?

The average time complexity of put() and get() operations is O(1). In the worst case (hash collisions), it can degrade to O(log n) (since Java 8 uses tree-based buckets).







Q4.  How does HashMap differ from Hashtable?
  • HashMap is not synchronized (faster, not thread-safe).
  • Hashtable is synchronized (thread-safe but slower).
  • HashMap allows one null key, Hashtable does not.





Q5. How does HashMap handle collisions?

HashMap resolves collisions using chaining. Initially, collisions are stored as linked lists in a bucket, but from Java 8 onwards, when the list size exceeds a threshold, it is converted into a balanced tree for better performance.