Solution to 710c: The consequences of overriding equals
See code at solutions/code/tutorialquestions/question710c
Look at nohashcode/PointHash``CodeDemo.java
to see what can go wrong if you override equals
but do not override hashCode
.
To see an acceptable implementation of hashCode
for Point
, look at hashcode/Point.java
.
In this implementation, I use each double
field of Point
to make a Double
object,
and call hashCode
on the resulting objects. The Point
's hash code is then constructed by combining
these hash codes using the bitwise exclusive-or operator (^
). There are many other acceptable ways to implement
hashCode
, in terms of meeting the requirements of equals
. You could simply return a constant (stupid,
but acceptable in this context), or you could add up the double
fields and return the result, cast to an int
.
You do not need to override hashCode
in ColouredPoint
for the requirements of equals
to be
met: if two coloured points are equal then certainly they are equal when regarded as points, and thus Point
will give them
the same hash code.
However, in practice, it is beneficial to use the additional colour field of a ColouredPoint
to make ColouredPoint
s'
hash codes more diverse. You will see in hashcode/ColouredPoint.java
that I've overidden hashCode
to return the existing
Point
hash code, xor-ed with the hash code of the colour
field (which in my implementation is an enum).