Serializing and deserializing a map with key as string
Posted
by Grace K
on Stack Overflow
See other posts from Stack Overflow
or by Grace K
Published on 2010-04-30T21:31:20Z
Indexed on
2010/04/30
21:57 UTC
Read the original article
Hit count: 284
Hi!
I am intending to serialize and deserialize a hashmap whose key is a string.
From Josh Bloch's Effective Java, I understand the following. P.222 "For example, consider the case of a harsh table. The physical representation is a sequence of hash buckets containing key-value entries. Which bucket an entry is placed in is a function of the hash code of the key, which is not, in general guaranteed to be the same from JVM implementation to JVM implementation. In fact, it isn't even guranteed to be the same from run to run on the same JVM implementation. Therefore accepting the default serialized form for a hash table would constitute a serious bug. Serializing and deserializing the hash table could yield an object whose invariants were seriously corrupt."
My questions are: 1) In general, would overriding the equals and hashcode of the key class of the map resolve this issue and the map can be correctly restored?
2) If my key is a String and the String class is already overriding the hashCode() method, would I still have problem described above. (I am seeing a bug which makes me think this is probably still a problem even though the key is String with overriding hashCode.)
3)Previously, I get around this issue by serializing an array of entries (key, value) and when deserializing I would reconstruct the map. I am wondering if there is a better approach.
4) If the answers to question 1 and 2 are that I still can't be guaranteed. Could someone explain why? If the hashCodes are the same would they go to the same buckets across JVMs?
Thanks, Grace
© Stack Overflow or respective owner