I’ve recently been going through some Java headaches of late. I wrote a class whose purpose was to be a wrapper for another class but that offers a sorting ability not offered by that original class. I implemented an equals method but never really understood, nor implemented the associated hashCode method. I’ve spent the better part of an entire day messing around with my code so that my unit tests showed that my code worked the way I expected it should. I’d never really knew of the relationship between the equals method and the hashCode method. So of course, I did the ol’ Google search and came up with the following link that seems to give a relatively good explanation.
I further enhanced what was demonstrated in that article by discovering the following two Apache commons “helper” classes that make implementing equals and hashCode that much easier:
So now that I’ve implemented equals and hashCode as well as my Comparable interface, everything sorts and determines equality as I expect it to. Such a huge headache for such a small inconsequential class…lol. Oh well, I’ll know better next time.