When I was looking at the source code of ArrayList, I saw that the actual array that holds the data items was defined as
I had no idea what transient meant. So I looked it up, but before explaining what transient means and why elementData in ArrayList is defined as transient, I first need to explain what Serializable means in Java.
To serialize an object means to convert its state to a byte stream so that the byte stream can be reverted back into a copy of the object. A Java object is serializable if its class or any of its superclasses implements either the java.io.Serializable interface or its subinterface, java.io.Externalizable. Deserialization is the process of converting the serialized form of an object back into a copy of the object.
Serialization is used mostly for network programming. So if you want to send an object through a network, you serialize it, send and deserialize it at the other end.
What transient keyword does is that it tells compiler that that object should NOT be serialized, in other words should not be converted into a byte stream.
After learning these, I still hadn’t understood why elementData was defined as transient, why ArrayList was not serializable.
Actually, it is. ArrayList class implements two methods for serialization called writeObject and readObject. They were defined separately and elementData was defined as transient, because if you defined an array list in your program, it is highly possible that many of its elements is actually null, and there is no need to put null elements in the byte stream when you serialize it, it’s a waste of space. What those methods do is that they ignore those null elements, and just serialize/deserialize only not null elements after going through elementData.