java hashset 序列化,Java hashset如何序列化多个对象

该博客讨论了如何在Java中使用HashSet进行对象序列化和反序列化。作者遇到了在尝试将HashSet的每个元素单独保存为.ser文件时遇到的问题。解决方案是直接序列化整个HashSet,而不是其单个元素,确保所有对象实现Serializable接口,然后在需要时反序列化回HashSet,以保持对象的状态不变。
摘要由CSDN通过智能技术生成

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 hSet = new HashSet();

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

}

}

}

}

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?

解决方案

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值