You are right about the fact that ==
compares the references of the two variables, but, references are not the same as hash codes.
Hash codes are numbers returned by this method that you’ve written:
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
While references are memory locations at which the objects are stored. They are completely different.
It is understandable that you have this misconception. If you did not override hashCode
, it would have returned the memory location of the object, so the hash code would have been the same as the memory location. However, since you have overridden hashCode
, they are not the same any more.
3
solved Object comparison using == operator in Java