2010-11-29 23 views
2

我正在構建一個android應用程序,我想添加一個歷史記錄功能。我聽說我可以序列化一個列表,以便能夠保存和檢索數據,而不是使用數據庫,我不知道它是如何工作的,所以我來這裏尋求建議,有沒有什麼地方可以開始使用它。一些好的鏈接可能會有用。如何序列化HashSet

感謝

回答

2

你不應該使用可序列化的,以更有效的方式實現可執行文件。問題是你必須定義自己如何包裹對象,但它確實不是那麼難。

簡單的例子:

public class MyParcelable implements Parcelable { 
    private int mData; 

    public int describeContents() { 
     return 0; 
    } 

    public void writeToParcel(Parcel out, int flags) { 
     out.writeInt(mData); 
    } 

    public static final Parcelable.Creator<MyParcelable> CREATOR 
      = new Parcelable.Creator<MyParcelable>() { 
     public MyParcelable createFromParcel(Parcel in) { 
      return new MyParcelable(in); 
     } 

     public MyParcelable[] newArray(int size) { 
      return new MyParcelable[size]; 
     } 
    }; 

    private MyParcelable(Parcel in) { 
     mData = in.readInt(); 
    } 
} 

如果你想保存HashSet的,你只需要確保哈希裏面的對象也是parcelable。

如果您覺得這太麻煩了,Nailuj以前發佈的答案是正確的。

+0

感謝您的答案,我給一個嘗試@blindstuff爲例,來看看他它去;) – 2010-11-29 20:20:05

16

HashSet實現Serializable。因此,只要你放置在你的哈希集中的所有對象也實現了Serializable(以及它們內部的所有對象等等),就可以將它序列化爲任何其他正常的可序列化Java對象。