Java – is the order of variables important in packet change read / write operations in Parcelable?

I have the following implementation of a 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
}

Is it important to maintain order when writing / reading packages? Why?

Solution

Yes, it does The order in which variables are written depends on you. You can operate as needed, but you must read them in the same order If the order is different, it will give you a runtime crash

Why? The mechanism is blind, so it believes you can get it in the right order The main purpose is to gain performance advantages because it does not have to search for specific elements You can see in the Parcelable interface that the size of the array it creates is multiple elements you put into the parcel

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);
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>