(Java) 14.8 hashCode implementation

#1

Hi,

The Person class has hashCode defined in terms of name and age, but the equals method uses only the age. Furthermore, the compareTo method also uses only the age.
Isn’t a problem having two separate rulesets for hash and equal comparison?

0 Likes

#2

this one is pretty subtle, it’s a good catch. the Person class was broken, would have failed elementary properties of a hash table.

this did not affect the code because in fact we do not need to implement comparable, equals, or hashCode, for the program, and i have removed all of these.

ordering is explicitly not needed. the equals/hashcode methods were just there for testing. i removed the hashset used in the test code, used an arraylist in its place, and we should be good. (we dont need equals/hashcode/compareto since we use the integer-valued age explicitly (Integer of course correctly implements these methods)

0 Likes