[英]Java hashset how to serialise multiple objects
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. 我问了一个先前的问题,关于如何将多个保存文件保存到.ser文件中,建议我使用哈希集,因为它们是可序列化的。 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();
}
}
}
}
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
. 但是我在获取代码来编写带有index(i)对象的代码时遇到了麻烦,因为它说该方法没有为
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.
只要确保testClass实现了Serializable,并且其所有字段都实现了。
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. 当您想反序列化并读取对象时,将其
HashSet<testClass>
为HashSet<testClass>
,它将保持序列化之前的状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.