Java hashset如何序列化多个对象 [英] Java hashset how to serialise multiple objects

查看:167
本文介绍了Java hashset如何序列化多个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我问过一个关于如何将多个保存文件保存到.ser文件的问题,我被建议使用一个hashset,因为它们是可序列化的。我试图编写一段测试代码来序列化哈希集中的每一条信息:

I asked a previous question about how I would save multiple save files to a .ser file, and I was suggested to use a hashset because they are serializable. I have tried to write a test piece of code to serialize every piece of information inside the hash set:

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();
            }
        }
    }
}

但是我在使用索引(i)编写对象的代码时遇到了麻烦,因为它说没有为类型 HashSet 定义该方法。有没有办法迭代哈希集中的每一条信息,或者我应该一次串行化整个集合。另一个问题是,如果第一个答案是后者,我将如何将数据反序列化为单独的类?

However I'm having trouble with getting the code to write the object with index(i), because it says that that method is not defined for the type HashSet. Is there a way to iterate through every piece of information in the hash set or should I serialise the whole set all at once. A further question is that if the first answer is the latter, how would I go about deserialising the data into separate classes?

推荐答案

解决方案:序列化哈希集本身。只需确保testClass实现Serializable及其所有字段都这样做。

Solution: Serialize the hashset itself. Just make sure testClass implements Serializable and all of its fields do so to.

当你想要反序列化它并读取对象时,你将它转换为 HashSet< testClass> 它会在序列化之前保持其状态。

When you want to unserialize it and read the object, you cast it to HashSet<testClass> and it will maintain its state as before you serialized it.

这篇关于Java hashset如何序列化多个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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