Re: HashMaps, hashcodes, equals, and Serialization
- From: Lew <lew@xxxxxxxxxxx>
- Date: Sat, 30 Dec 2006 10:46:46 -0500
Siam wrote:
Hi 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.
Questions:
1) How compulsory is it to overload the hashcode method, having
overloaded the equals method.
It is very compulsory, except when you have a distinct reason to make them inconsistent. Even then it's compulsory, you just might have a reason to disregard the rule.
No "Hash.+" anything will work correctly if hashCode() and equals() are inconsistent. That is why they have "Hash" in their names!
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?
Your serialization format should not in any way depend on the hash. If it does, then you have not written your readObject)() and writeObject() methods correctly.
Read Joshua Bloch's _Effective Java Programming_, which has chapters covering both these questions in detail.
- Lew
.
- References:
- Prev by Date: Re: Exception thrown & Failure in loading T2 native library db2jcct2 while connecting to db2/400 through java
- Next by Date: Re: How to check variables for uniqueness ?
- Previous by thread: HashMaps, hashcodes, equals, and Serialization
- Next by thread: Re: HashMaps, hashcodes, equals, and Serialization
- Index(es):
Relevant Pages
|