1. What is HashMap in Java?
Answer:
Explanation:
HashMap is a collection in Java that stores data in key-value pairs, allowing for fast retrieval.
2. What interface does HashMap implement?
Answer:
Explanation:
HashMap implements the Map interface in Java.
3. Can a HashMap contain duplicate keys?
Answer:
Explanation:
In a HashMap, each key is unique. Adding a new entry with an existing key replaces the old value with the new one.
4. Is HashMap ordered?
Answer:
Explanation:
HashMap does not maintain any order of its entries, neither insertion order nor natural ordering.
5. Can a HashMap contain null values?
Answer:
Explanation:
HashMap allows null values and even one null key.
6. What is the default initial capacity of a HashMap in Java?
Answer:
Explanation:
The default initial capacity of a HashMap is 16.
7. How does HashMap handle collisions?
Answer:
Explanation:
HashMap handles collisions by storing collided elements in a linked list or tree structure at the same index.
8. What method do you use to get a value from a HashMap?
Answer:
Explanation:
The get() method is used to retrieve a value from a HashMap using its key.
9. How do you remove a key-value pair from a HashMap?
Answer:
Explanation:
The remove() method is used to remove a key-value pair from a HashMap.
10. What happens if you put a key-value pair with an existing key in a HashMap?
Answer:
Explanation:
If a key already exists in the map, putting a new value for that key will replace the old value.
11. What is the time complexity of the get() and put() methods in HashMap?
Answer:
Explanation:
In most cases, the get() and put() methods in HashMap have a time complexity of O(1).
12. How can you iterate over a HashMap?
Answer:
Explanation:
A HashMap can be iterated using an iterator or a for-each loop over the entrySet, keySet, or values.
13. What method checks if a HashMap contains a specific key?
Answer:
Explanation:
The containsKey() method is used to check if a particular key exists in the HashMap.
14. What does the clear() method do in a HashMap?
Answer:
Explanation:
The clear() method removes all of the mappings from the map.
15. Can a HashMap be synchronized?
Answer:
Explanation:
While HashMap itself is not synchronized, it can be wrapped with Collections.synchronizedMap() to make it synchronized.