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 hash 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
guaranteed 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 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 got 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 it 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
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…