As per the below link
So it is assumed that if 2 objects are equal (that is, equals() returns true), then their hashCodes() must return the same value.
But consider the below example
public class Test {
public static void main(String args[]) {
Demo d1 = new Demo(123);
Demo d2 = new Demo(123);
System.out.println("d1.hashCode()-->" + d1.hashCode());
System.out.println("d2.hashCode()-->" + d2.hashCode());
System.out.println(d1.equals(d2));
}
}
class Demo {
private int name;
Demo(int name) {
this.name = name;
}
@Override
public int hashCode() {
Double d = Math.random() * 1000;
return d.intValue();
}
@Override
public boolean equals(Object o) {
if ((o instanceof Demo) && (((Demo) o).getName() == this.getName())) {
return true;
} else {
return false;
}
}
public int getName() {
return name;
}
}
the output of the above program is
d1.hashCode()-->85
d2.hashCode()-->692
true
Here the question is even though the hash code is different the equals method return true. So does it mean for equality of object we do not need same hash code