簡體   English   中英

Java hashset如何序列化多個對象

[英]Java hashset how to serialise multiple objects

我問了一個先前的問題,關於如何將多個保存文件保存到.ser文件中,建議我使用哈希集,因為它們是可序列化的。 我試圖編寫一段測試代碼來序列化哈希集中的每條信息:

public class testHashSet {
    public static void main(String[] args) throws ClassNotFoundException {
        testClass new1 = new testClass("Hello", "male", true);
        testClass new2 = new testClass("Goodbye", "female", true);
        testClass new3 = new testClass("Something", "other", false);
        HashSet<testClass> hSet = new HashSet<testClass>();
        hSet.add(new1);
        hSet.add(new2);
        hSet.add(new3);
        System.out.println(hSet);
        for(int i = 0; i < hSet.size(); i++) {
            try {
                FileOutputStream fileOut = new FileOutputStream("/Users/Prodigy958/Desktop/Hack_exeSaves.ser");
                ObjectOutputStream out = new ObjectOutputStream(fileOut);
                out.writeObject(hSet(i));
                out.close();
                fileOut.close();
            } catch(IOException i) {
                i.printStackTrace();
            }
        }
    }
}

但是我在獲取代碼來編寫帶有index(i)對象的代碼時遇到了麻煩,因為它說該方法沒有為HashSet類型定義。 有沒有辦法遍歷哈希集中的每條信息,還是我應該一次序列化整個集合呢? 另一個問題是,如果第一個答案是后者,我將如何將數據反序列化為單獨的類?

解決方案:序列化哈希集本身。 只要確保testClass實現了Serializable,並且其所有字段都實現了。

當您想反序列化並讀取對象時,將其HashSet<testClass>HashSet<testClass> ,它將保持序列化之前的狀態。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM