Junior — Middle
В каких ситуациях объекты, являющиеся неэквивалентными, могут иметь одинаковое значение хеш-кода?
sobes.tech AI
Answer from AI
In Java, objects that are not equal (not equivalent) can have the same hash code due to hash collisions. A hash function maps a large set of possible objects to a limited range of integers (usually 32-bit), so different objects can produce the same hash code.
This is normal and expected, so when implementing the hashCode() and equals() methods, it is important to follow the contract:
- If two objects are equal (
equals()returnstrue), their hash codes must be the same. - If objects are not equal, their hash codes can be the same, but this degrades the performance of hash-based data structures (e.g.,
HashMap).
Example:
String a = "FB";
String b = "Ea";
System.out.println(a.hashCode()); // 2236
System.out.println(b.hashCode()); // 2236
System.out.println(a.equals(b)); // false
Here, the strings are different, but their hash codes match.