Junior — Middle
What is the difference between Serializable and Parcelable interfaces when passing objects in Android?
sobes.tech AI
Answer from AI
Serializable and Parcelable are interfaces for object serialization in Android, but they have different characteristics:
-
Serializable — a standard Java interface. It is easy to use (just implement the interface), but it works slower and creates more overhead during serialization.
-
Parcelable — a specific Android interface that requires manual implementation of methods for writing and reading data. It operates much faster and more efficiently, which is important for passing objects between Android components (e.g., via
IntentorBundle).
Example of using Parcelable:
public class User implements Parcelable {
private String name;
private int age;
protected User(Parcel in) {
name = in.readString();
age = in.readInt();
}
public static final Creator<User> CREATOR = new Creator<User>() {
@Override
public User createFromParcel(Parcel in) {
return new User(in);
}
@Override
public User[] newArray(int size) {
return new User[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeInt(age);
}
}
Therefore, for passing objects in Android, it is preferable to use Parcelable due to its performance benefits.