在Parcelable中进行包裹读/写操作时,可变顺序是否重要? [英] Does variable order matter while parcel read/write operation in Parcelable?

查看:110
本文介绍了在Parcelable中进行包裹读/写操作时,可变顺序是否重要?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 Parcelable 类的实现:

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 while write/read to the parcel? And why?

推荐答案

是的.写入变量的顺序由您决定,您可以根据需要进行操作,但是必须以相同的顺序读取它们.如果顺序不同,它将给您运行时崩溃.

Yes it does. Order of write variables is up to you and you can do it as you want, but you must read them in that same exact order. It will give you runtime crash if order will be different.

为什么?机制是盲目的,因此它信任您以正确的顺序进行操作.主要是为了提高性能,因为它不必搜索特定的元素.您可以在 Parcelable 界面中看到,它创建的数组的大小与您放入包裹的元素数相同.

Why? Mechanism is blind, so it trust you to get it in right order. Mostly for performance benefits, because it don't have to search for a specific element. You can see in Parcelable interface, that it creates array with size of a number of elements you put in 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);
}

这篇关于在Parcelable中进行包裹读/写操作时,可变顺序是否重要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆