Junior — Middle
What are the consequences if two objects have the same hash code?
sobes.tech AI
Answer from AI
If two objects have the same hash code, this is called a hash collision. In Java, this is normal and expected, since the hash code is an int, and there can be many more objects. Consequences:
- Collisions can lead to decreased performance of hash data structures (e.g., HashMap or HashSet), as objects with the same hash code will be stored in the same bucket, and comparison using equals() will be necessary during search.
- It is important that, when hash codes are equal, the equals() method correctly distinguishes objects, otherwise data may be overwritten or lost.
Example:
Map<MyObject, String> map = new HashMap<>();
// If MyObject overrides hashCode() but not all fields are considered in equals(),
// errors may occur when working with the collection.