亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

ArrayList中為什么size要序列化兩次?

在代碼中s.defaultWriteObject();中size應該也被序列化了,為什么下邊還要再單獨序列化一次呢?

正在回答

1 回答

這樣寫是出于兼容性考慮。

舊版本的JDK中,ArrayList的實現有所不同,會對length字段進行序列化。

而新版的JDK中,對優化了ArrayList的實現,不再序列化length字段。

這個時候,如果去掉s.writeInt(size),那么新版本JDK序列化的對象,在舊版本中就無法正確讀取,

因為缺少了length字段。

因此這種寫法看起來多此一舉,實際上卻保證了兼容性。

附上官方解釋:defaultReadObject()?and?defaultWriteObject()?should?be?the?first?method?call?inside?readObject(ObjectInputStream?o)?and?writeObject(ObjectOutputStream?o).?It?reads?and?writes?all?the?non-transient?fields?of?the?class?respectively.?

These?methods?also?helps?in?backward?and?future?compatibility.?If?in?future?you?add?some?non-transient?field?to?the?class?and?you?are?trying?to?deserialize?it?by?the?older?version?of?class?then?the?defaultReadObject()?method?will?neglect?the?newly?added?field,?similarly?if?you?deserialize?the?old?serialized?object?by?the?new?version?then?the?new?non?transient?field?will?take?default?value?from?JVM?i.e.?if?its?object?then?null?else?if?primitive?then?boolean?to?false,?int?to?0?etc….

11 回復 有任何疑惑可以回復我~

舉報

0/150
提交
取消

ArrayList中為什么size要序列化兩次?

我要回答 關注問題
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號