This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Short Tale From The Frontlines This falls under "JAVA 101" which I learned very well almost three years ago but just bit me at work yesterday when another programmer wrote a class which was intended to be used as a key in a HashMap in another one of his classes. I inherited (no pun intended! ) his work and I spent a lot of time finding out why a key present in a HashMap could not find an object already stored in it. Well it turned out (and I'm proud of finding out what the problem was which I could have only found if I studied like I did for the SCPJ2 certification) that the original programmer failed to override the hashCode() method of the Object class and of course the keys could never be found that matched the desired Objects. Moral of the story: If the objects instantiating your classes are ever going to be used as keys in a "HashSomething", you have to override Object.hashCode() in your new class (returns an int). As I said, I learned that a long time ago when I was studying Java full time, but the actual situation never presented itself until now, after two full years as a Web Component Developer in Java.
Tony Alicea Senior Java Web Application Developer, SCPJ2, SCWCD
An excellent point. Note that this is the sort of thing that doesn't necessarily show up as a problem right away - the HashMap will only fail to behave as expected under certain circumstances. Additionally, any time you override hashCode(), you should also override equals() (and vice versa) so the two methods are consistent. The rules to be obeyed are explained in the API for hashCode() and equals() (under Object). Joshua Bloch's "Effective Java" explains the implications well. (Does anyone know a good online link for this topic, other than the API?) To be honest, the principles are rather advanced for the "Beginner" forum - I'd say the here rule is, do not use instances of your own classes as keys in HashMaps until you've understood the use of hashCode() and equals(), and are reasonably confident you've implemented them correctly. Heck, 95% of the time I use a HashMap, the key is a String anyway - there's often no need for a new class for the key. [ April 06, 2002: Message edited by: Jim Yingst ]
I was just about to post a query asking why the following code could output "true", "false" (facts is a HashSet).
Amazingingly luckily I chanced upon this post and discovered my problem (HashSets are backed by HashMaps). So sometimes your own objects are used as keys for a HashMap without even realising- so beware !! thanks ! Tom