Why do we implement .hashCode() and .equals() everytime?

Hello everyone :slight_smile:

During reading through all the exercise sheets of the past lectures, I was wondering why exactly we always want to override the functions .hashCode() and .equals() for own classes with a native implementation?
Following some forum threads and websites like this or that, every object in java has already got a well-defined implementation for both functions.

Is it just for educational purposes? Or has it any special reason?

Thanks in advance,
David

We don’t always want to do so. We usually distinguish between classes that “are useful values” and classes that are only there to organize code. The former should have useful equals() methods, for the latter, it does not matter.

1 Like

okay, thanks for your answer.

But for me it’s still unclear, why we DO sometimes override the .equals() and .hashCode() function, if there are already useful and well-defined function implementations for all Java Objects.

For Exercise 10.: Modified Content, I tried removing the custom implementations of these functions and just use the given functions, and interestingly the ouput did change to:

true
true
true
true
Output with overridden implementation was....
true
true
false
true

So, the provided implementation of .equals in that exercise was wrong then, right?

Thanks!

No, the provided implementation of hashCode does not respect equals. This leads to interesting results.

Because rather often, identity is not the equality we want for our data.

1 Like

As an example:
You write a string class.
Now the user creates a string instance s1=new FancyString("Hello") and another independent instance s2=new FancyString("Hello").
The default equality does not (and can not) know your semantic intent and (as explained here) uses identity as equality relation.

But this leads s1.equals(s2) to be false.
A programmer would assume that two strings with the same characters are equal.
Therefore, you need to implement a custom equals method in order to have larger equality classes such that s1 and s2 can be viewed as equal.

Another example could be fractions with numerator and denominator that are viewed as equal if their numeric value is the same.

3 Likes