Middle
What is the difference between Serializable and Parcelable in Android?
sobes.tech AI
Answer from AI
The main difference lies in performance and implementation method.
-
Serializable:- Standard interface from Java SE.
- Easier to implement (just implement the interface).
- Uses Java Reflection API for serialization, which is slower and requires more memory.
- Suitable for small objects or when serialization performance is not critical.
-
Parcelable:- Specific interface for Android SDK.
- Requires explicit description of the serialization/deserialization process.
- Significantly faster and more memory-efficient as it does not rely on Reflection.
- The best choice for passing objects between Android components (Activity, Service, BroadcastReceiver) and saving state.
To implement Parcelable, you need to:
- Implement the
Parcelableinterface. - Implement the
writeToParcel()method to write data into aParcel. - Implement the
describeContents()method. - Create a static
CREATORobject that implements theParcelable.Creatorinterface.
import android.os.Parcel;
import android.os.Parcelable;
public class MyParcelableObject implements Parcelable {
private int value;
private String name;
public MyParcelableObject(int value, String name) {
this.value = value;
this.name = name;
}
protected MyParcelableObject(Parcel in) {
value = in.readInt();
name = in.readString();
}
public static final Creator<MyParcelableObject> CREATOR = new Creator<MyParcelableObject>() {
@Override
public MyParcelableObject createFromParcel(Parcel in) {
return new MyParcelableObject(in);
}
@Override
public MyParcelableObject[] newArray(int size) {
return new MyParcelableObject[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(value);
dest.writeString(name);
}
}
Comparison table:
| Attribute | Serializable | Parcelable |
|---|---|---|
| Library | java.io |
android.os |
| Performance | Low (uses Reflection) | High |
| Memory efficiency | Low | High |
| Implementation | Simpler | More complex |
| Usage | General Java, small data | Android, passing data between components |