Serialization method of custom objects in Android:
- Implements parcelable
- Implements serializable.
I. serialization reason:
- Permanently Save the object and save the object's byte sequence to a local file;
- Passing objects in the network by serializing objects;
- Objects are passed through serialization between processes.
2. for which to choose, refer to the following principles:
- When using memory, parcelable has higher performance than serializable. Therefore, parcelable is recommended.
- Serializable will generate a large number of temporary variables during serialization, resulting in frequent GC.
- Parcelable cannot be used when you want to store data on a disk, because parcelable cannot guarantee data continuity in the case of external changes. Although serializable is not recommended for low efficiency, we recommend that you use serializable in this case.
Three implementations:
- To implement serializable, you only need to inherit implements serializable. This only marks the object and the system will automatically serialize it.
- To implement parcelabel, you must add a static member variable creator to the class. This variable must inherit the parcelable. Creator interface.
public class MyParcelable implements Parcelable { private int mData; public int describeContents() { return 0; } public void writeToParcel(Parcel out, int flags) { out.writeInt(mData); } public static final Parcelable.Creator<MyParcelable> CREATOR = new Parcelable.Creator<MyParcelable>() { public MyParcelable createFromParcel(Parcel in) { return new MyParcelable(in); } public MyParcelable[] newArray(int size) { return new MyParcelable[size]; } }; private MyParcelable(Parcel in) { mData = in.readInt(); } }