This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Could anyone please throw some light on why the serialization of Vector and ArrayList is handled differently?
The object element array used internally in ArrayList is marked transient but not in Vector. Vector uses default Serialization approach accept making the writeObject method synchronized while ArryList manually writes and reads every element.
Girish K Gupta
SCJP 1.5 - 87%, SCWCD 1.5 - 92%
I've looked at the source code of the ArrayList.writeObject() method.
I think the reason why it has its own writeObject() method rather than relying on the default (built-in) serialization is because it needs to check for modifications in the method, throwing a ConcurrentModificationException if the ArrayList was modified by another thread while it was busy writing its contents to a stream.
That won't work for ArrayList, because its internal Object array is declared transient, and defaultwriteObject() doesn't write transient fields to the stream.
Writing the array's size and actual contents instead of the entire array itself is slightly more efficiënt, because the array would add it's own overhead to the serialization process.
Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
Why not just give it a try?
Initialize an Object array, and stuff one String into it. Serialize the int returned by the array's length property, using an ObjectOutpuStream#write, followed by the String instance using ObjectOutpuStream#writeObject() to a file. Then serialize the entire array, using ObjectOutpuStream#writeObject() to another file. You should be able to get a pretty good impression of the difference between these two files using any HEX editor.
Yes Jelle I noticed the difference. Tried serializing object of an ArrayList and a Vector filled with same objects.
In my case serialized ArrayList object took 230 bytes while serialized Vector object took 335 bytes of memory.