you pesky little hashCode()…
Bugs can be quite frustrating but very educational. My day started off with a project using Spring MVC. I had two properties on an object of the same type, basically:
MyObject foo = new MyObject();
MyObject foo2 = new Myobject();
Now comes the really fun part. These objects were bound to a form in the web page with a spring-form select:
<spring-form:select path="foo.id">...
<spring-form:select path="foo2.id">...
Everytime I saved the page foo2’s value it would be bound correctly but foo would have foo2’s value bound to it as well. My first instinct was to check the path, then check it 5 more times on the .jsp and yell frustratingly that they are different. Next option, turn on showSql for my OpenJpa, and see what values were being set in the sql being passed. When that all turned up blank I checked out my MyObject class and scanned the setters/getters and tracked their usages. Finally, I just put a lot of logging in. Everything seemed correct!!!
That is when nothing makes sense for a developer because you swear everything is right so you know what, it is Spring’s fault! So I did the normal worked on something else then came back to it an hour later and took another peek for the 84th time of the day and noticed that we were overriding equals but not the hashcode! So as everyone already knew the solution to the problem from the title, the darn hashCode was never implemented in the class.
It was a simple overlook by whoever created the class, but those simple fundamental rules that everyone is taught are important to follow. It also makes me realize I should learn more of how some of the underlying code works in java and spring so that I will be able to identify issues like this quicker. Funny how this one issue has become one of the most enlightening bugs I have solved!
November 15th, 2008 at 2:38 am
Static analysis tools like findbugs help in finding such problems. It is always a good idea to run findbugs on your java application once..