Negative hashCodes are fine. Given what you've shown below, I'd say that the Foo class didn't actually override both hashCode() and equals(), or you didn't do it properly. You've got to override both for this to work correctly, such that f1.equals(toBeDeleted) returns true, and f1.hashCode() == toBeDeleted.hashCode() .
Ernest, thanks for your reply. Here's another conundrum:
Notice the last line. Why is it behaving like this ? Just to give you a bit more info; the code above only fails when it's within a domain object using Hibernate framework. But it works fine from the command line ? I am at a loss ? Regards, Pho
Ernest's previous response applies equally well here. If you override hashCode() wothout correctly overriding equals() as well - or vice versa - then the methods of HashMap, Hashtable, and HashSet will not function as expected. Details of how to override hashCode() and equals() can be found in most introductoray Java texts - the Java Tutorial is one example.
Jim, My equals/hashCode() works fine in my Junittest cases. I implemented them following: http://www.geocities.com/technofundo/tech/java/equalhash.html But it fails to work when deployed to the container. Regards, Pho
Here's one theory: you made the common mistake of implementing equals() like this: public boolean equals(Foo arg) ... using the type of the class as the type of the method parameter. This overridden equals won't be used by the container; the container will continue to use the default version of equals.