守着一只汪
好问题.原因当然如@Windoze所言,有效率的考虑,但还有更深的原因.EffectiveJava2nd,Item75,Joshua大神提到:Forexample,considerthecaseofahashtable.Thephysicalrepresentationisasequenceofhashbucketscontainingkey-valueentries.Thebucketthatanentryresidesinisafunctionofthehashcodeofitskey,whichisnot,ingeneral,guaranteedtobethesamefromJVMimplementationtoJVMimplementation.Infact,itisn'tevenguaranteedtobethesamefromruntorun.Therefore,acceptingthedefaultserializedformforahashtablewouldconstituteaseriousbug.Serializinganddeserializingthehashtablecouldyieldanobjectwhoseinvariantswereseriouslycorrupt.怎么理解?看一下HashMap.get()/put()知道,读写Map是根据Object.hashcode()来确定从哪个bucket读/写.而Object.hashcode()是native方法,不同的JVM里可能是不一样的.打个比方说,向HashMap存一个entry,key为字符串"STRING",在第一个java程序里,"STRING"的hashcode()为1,存入第1号bucket;在第二个java程序里,"STRING"的hashcode()有可能就是2,存入第2号bucket.如果用默认的串行化(Entry[]table不用transient),那么这个HashMap从第一个java程序里通过串行化导入第二个java程序后,其内存分布是一样的.这就不对了.HashMap现在的readObject和writeObject是把内容输出/输入,把HashMap重新生成出来.