Senior
Question 2. What can go wrong with HashMap if all keys have the same hashCode? - Searching by key will not return the correct object - Searching by key will slow down - Searching by key will not return the object
sobes.tech AI
Answer from AI
If all keys in a HashMap have the same hashCode(), then they will all fall into the same bucket. This leads to the following consequences:
- Search by key will slow down, as instead of quick access via hash, all elements in one chain (or tree, if many) will need to be traversed.
- Search by key will still return the correct object if the key exists, because key comparison is done via
equals().
Therefore, the correct answer is: Search by key will slow down.
Example:
Map<Key, Value> map = new HashMap<>();
// All keys have the same hashCode
// During search, all elements in one bucket will be traversed