在 Parcelable 中执行 parcel read/write 操作时可变顺序是否重要?

Does variable order matter while parcel read/write operation in Parcelable?

我有以下 Parcelable class 的实现:

public class DemoModel implements Parcelable {
    private String para1;
    private int para2;

    public DemoModel(){}

    protected DemoModel(Parcel in) {
        para1 = in.readString();
        para2 = in.readInt();
    }

    @Override
    public void writeToParcel(Parcel parcel, int i) {
        parcel.writeString(para1);
        parcel.writeInt(para2);
    }

    //other methods
}

在write/read收到包裹的同时维持秩序重要吗?为什么?

根据this source

One very important thing to pay close attention to is the order that you write and read your values to and from the Parcel. They need to match up in both cases.

这是由其创建者实施 parcelable 的方式造成的

是的。写入变量的顺序由您决定,您可以按照自己的意愿进行,但您必须以相同的顺序读取它们。如果顺序不同,它会给你运行时崩溃。

为什么?机制是盲目的,所以它相信你能按正确的顺序得到它。 主要是为了提高性能,因为它不必搜索特定元素。 您可以在 Parcelable 界面中看到,它创建的数组的大小为您放入包裹中的元素数量。

public interface Creator<T> {
    /**
     * Create a new array of the Parcelable class.
     * 
     * @param size Size of the array.
     * @return Returns an array of the Parcelable class, with every entry
     * initialized to null.
     */
    public T[] newArray(int size);
}