HashMaps, hashcodes, equals, and Serialization
807607Dec 30 2006 — edited Dec 30 2006Hi all,
As part of my application, I have an ArticleManager class, that maintains a HashMap of Article objects (which have an overloaded equals method - but not an overloaded hashcode). When my application is closed, the ArticleManager serializes itself and all the Articles. These are then deserialized when my application reloads again. Questions:
1) How compulsory is it to overload the hashcode method, having overloaded the equals method. If I don't, will this mean my HashMap won't function correctly - i.e. if "Article ar1" exists in the hashmap, and I call get(ar2) on the hashmap, such that ar1.equals(ar2), would it not return me ar1, since their hashcodes are difference? Does the HashMap code ever test for equality itself when putting and getting objects, or does it simply rely on the contracted relationship between hashcode() and equals()? How would I go about writing an effective custom hashcode function?
2) The contract for hashcode, as written in the API, states "This integer [the hashcode] need not remain consistent from one execution of an application to another execution of the same application." Will this cause complications for when my articles and the hashmap are serialized, and later deserialized on another execution of my application? In that, surely if the hashcode is used in determining where in the table a certain Article object is placed, then if the hashcode for the Article (when deserialized) changes on another execution of the application, would the hashmap still be able to find the Article in its previous place? Or does serialization/deserialization maintain the hashcode of the object?
Cheers :)
Siam