[android] Serializable 和 Parcelable 区别
android 中自定義的對象序列化的問題有兩個選擇一個是Parcelable,另外一個是Serializable。
一 序列化原因:
1.永久性保存對象,保存對象的字節序列到本地文件中;
2.通過序列化對象在網絡中傳遞對象;
3.通過序列化在進程間傳遞對象。?
二 至于選取哪種可參考下面的原則:
1.在使用內存的時候,Parcelable 類比Serializable性能高,所以推薦使用Parcelable類。
2.Serializable在序列化的時候會產生大量的臨時變量,從而引起頻繁的GC。
3.Parcelable不能使用在要將數據存儲在磁盤上的情況,因為Parcelable不能很好的保證數據的持續性在外界有變化的情況下。盡管Serializable效率低點, 也不提倡用,但在這種情況下,還是建議你用Serializable 。
實現:
1 Serializable 的實現,只需要繼承 ?implements Serializable 即可。這只是給對象打了一個標記,系統會自動將其序列化。
2 Parcelabel 的實現,需要在類中添加一個靜態成員變量 CREATOR,這個變量需要繼承 Parcelable.Creator 接口。
?
1 public class MyParcelable implements Parcelable { 2 private int mData; 3 4 public int describeContents() { 5 return 0; 6 } 7 8 public void writeToParcel(Parcel out, int flags) { 9 out.writeInt(mData); 10 } 11 12 public static final Parcelable.Creator<MyParcelable> CREATOR 13 = new Parcelable.Creator<MyParcelable>() { 14 public MyParcelable createFromParcel(Parcel in) { 15 return new MyParcelable(in); 16 } 17 18 public MyParcelable[] newArray(int size) { 19 return new MyParcelable[size]; 20 } 21 }; 22 23 private MyParcelable(Parcel in) { 24 mData = in.readInt(); 25 } 26 }?轉載地址:Serializable 和 Parcelable 區別(http://www.blogjava.net/lincode/archive/2011/09/16/358805.html)
轉載于:https://www.cnblogs.com/androidxiaoyang/archive/2013/03/25/2980463.html
總結
以上是生活随笔為你收集整理的[android] Serializable 和 Parcelable 区别的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Oracle Database 12c(
- 下一篇: 【JNI】javah使用(初步)