Junior — Middle
Can two objects that are considered different through equals() have the same hashCode() value?
sobes.tech AI
Answer from AI
Yes, in Java, two objects that are considered different through the equals() method can have the same hashCode() value.
This is because hashCode() returns an integer value of fixed size, while the number of possible objects is much larger than the number of possible hashes. Therefore, hash collisions are inevitable.
It is important that if two objects are equal according to equals(), they must have the same hashCode(). But the reverse is not necessarily true: having the same hashCode() does not guarantee equality according to equals().
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 "FB" and "Ea" have the same hash code but are not equal.