Here are 40 Java HashMap interview questions and answers suitable for candidates with 2 to 3 years of experience:
1. What is a HashMap in Java?
HashMap is a data structure that stores key-value pairs in Java. It implements the Map interface and uses hashing to store and retrieve elements efficiently.
2. How do you create a HashMap in Java?
You can create a HashMap using the HashMap class and the new keyword:
Map hashMap = new HashMap<>();
3. How do you add elements to a HashMap?
You can add elements to a HashMap using the put() method:
hashMap.put(key, value);
4. How do you retrieve a value from a HashMap?
You can retrieve a value from a HashMap using the get() method:
ValueType value = hashMap.get(key);
5. How do you check if a key exists in a HashMap?You can check if a key exists in a HashMap using the containsKey() method:
boolean containsKey = hashMap.containsKey(key);
6. How do you check if a value exists in a HashMap?
You can check if a value exists in a HashMap using the containsValue() method:
boolean containsValue = hashMap.containsValue(value);
7. How do you remove an element from a HashMap?
You can remove an element from a HashMap using the remove() method:
ValueType removedValue = hashMap.remove(key);
8. How do you get the number of elements in a HashMap?
You can get the number of elements in a HashMap using the size() method:
int size = hashMap.size();
9. How do you iterate over a HashMap?
You can iterate over a HashMap using various methods such as keySet(), entrySet(), or forEach():
// Using keySet()
for (KeyType key : hashMap.keySet()) {
ValueType value = hashMap.get(key);
// Perform operations with key-value pair
}
// Using entrySet()
for (Map.Entry entry : hashMap.entrySet()) {
KeyType key = entry.getKey();
ValueType value = entry.getValue();
// Perform operations with key-value pair
}
// Using forEach()
hashMap.forEach((key, value) -> {
// Perform operations with key-value pair
});
10. What happens if two keys have the same hash code in a HashMap?
If two keys have the same hash code, a collision occurs.
In a HashMap, collisions are resolved by chaining the elements in a linked list at the corresponding index.
11. How does HashMap handle hash code collisions?
HashMap handles hash code collisions by storing the colliding elements in a linked list at the corresponding index.
Each element in the list contains the key-value pair.
12. What is the difference between HashMap and HashTable?
The main differences are:
HashMap is not thread-safe, while HashTable is thread-safe.
HashMap allows null keys and values, while HashTable does not allow null keys or values.
HashMap is faster than HashTable.
13. How do you sort a HashMap by its keys?
You can sort a HashMap by its keys by converting it to a TreeMap, which automatically sorts the keys:
Map sortedMap = new TreeMap<>(hashMap);
14. How do you sort a HashMap by its values?
You can sort a HashMap by its values by creating a list of entries and sorting the list using a custom comparator:
List
15. What is the load factor in a HashMap?
The load factor is a measure of how full the HashMap is allowed to get before its capacity is automatically increased. It affects the performance and space efficiency of the HashMap.
16. What is the default load factor of a HashMap?
The default load factor of a HashMap is 0.75. This means that the HashMap can reach 75% of its capacity before it is resized.
17. How does the initial capacity and load factor affect the performance of a HashMap?
Choosing an appropriate initial capacity and load factor can improve the performance of a HashMap. A larger initial capacity reduces the number of rehashing and resizing operations, while a smaller load factor increases the number of elements that can be stored before resizing.
18. How do you increase the capacity of a HashMap?
The capacity of a HashMap is automatically increased when the number of elements exceeds the product of the load factor and the current capacity. You don't need to manually increase the capacity.
19. What happens if the initial capacity of a HashMap is too low?
If the initial capacity is too low, the HashMap may need to be resized frequently, resulting in performance degradation. It is recommended to provide an initial capacity that accommodates the expected number of elements.
20. How do you retrieve all the keys from a HashMap?
You can retrieve all the keys from a HashMap using the keySet() method:
Set keys = hashMap.keySet();
21. How do you retrieve all the values from a HashMap?
You can retrieve all the values from a HashMap using the values() method:
Collection values = hashMap.values();
22. How do you check if a HashMap is empty?
You can check if a HashMap is empty using the isEmpty() method:
boolean isEmpty = hashMap.isEmpty();
23. Can you use objects of custom classes as keys in a HashMap?
Yes, you can use objects of custom classes as keys in a HashMap. For this to work correctly, you need to override the hashCode() and equals() methods in your custom class.
24. Why is it important to override the hashCode() and equals() methods for objects used as keys in a HashMap?
Overriding the hashCode() and equals() methods ensures that the keys are compared correctly and that the elements are stored and retrieved from the HashMap accurately.
25. Can a HashMap contain duplicate values?
Yes, a HashMap can contain duplicate values. However, each key in a HashMap must be unique.
26. Can a HashMap contain null keys?
Yes, a HashMap can contain a single null key. However, it can contain multiple null values.
27. Can a HashMap contain null values?
Yes, a HashMap can contain multiple null values. However, it can contain only a single null key.
28. How do you copy the contents of one HashMap to another?
You can copy the contents of one HashMap to another using the putAll() method:
Map newHashMap = new HashMap<>();
newHashMap.putAll(hashMap);
29. What happens if you add a duplicate key to a HashMap?
If you add a duplicate key to a HashMap, the new value replaces the existing value associated with that key.
30. How do you replace a value for a given key in a HashMap?
You can replace a value for a given key in a HashMap using the put() method:
hashMap.put(key, newValue);
31. How do you replace a value in a HashMap only if the key exists?
You can replace a value in a HashMap only if the key exists using the replace() method:
ValueType replacedValue = hashMap.replace(key, newValue);
32. How do you replace a value in a HashMap only if the key and value match the existing entry?
You can replace a value in a HashMap only if the key and value match the existing entry using the replace() method:
boolean replaced = hashMap.replace(key, oldValue, newValue);
33. How do you remove all the elements from a HashMap?
You can remove all the elements from a HashMap using the clear() method:
hashMap.clear();
34. What is the difference between HashMap and LinkedHashMap?
The main difference is that LinkedHashMap maintains the insertion order of elements, while HashMap does not guarantee any specific order.
35. What is the difference between HashMap and TreeMap?
The main difference is that TreeMap sorts the elements based on their natural ordering or a custom comparator, while HashMap does not maintain any specific order.
36 How do you make a HashMap thread-safe?
You can make a HashMap thread-safe by using the ConcurrentHashMap class instead of HashMap. ConcurrentHashMap provides built-in thread-safety and concurrent access.
37. What is the time complexity of operations in a HashMap?
The time complexity of operations in a HashMap is generally O(1) on average, including put(), get(), containsKey(), and remove(). However, in the worst case scenario with many collisions, the time complexity can approach O(n), where n is the number of elements in the HashMap.
38. When should you use a HashMap over other data structures?
You should use a HashMap when you need a fast and efficient way to store and retrieve key-value pairs and when the order of elements is not important.
39. Can two threads simultaneously modify a HashMap?
In a standard HashMap, two threads modifying the HashMap simultaneously can result in an inconsistent state and data loss. To handle concurrent modifications, you can use ConcurrentHashMap or synchronize the access to the HashMap using external synchronization.
40. How does HashMap work internally?
HashMap uses an array of linked lists (buckets) and a hash function to store and retrieve elements. The hash code of the key determines the index in the array, and collisions are resolved by chaining elements in the linked lists.
No comments:
Post a Comment