【发布时间】:2016-07-20 19:13:52
【问题描述】:
我问过一个关于如何将多个保存文件保存到 .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 定义。有没有办法遍历哈希集中的每一条信息,或者我应该一次序列化整个集合。另一个问题是,如果第一个答案是后者,我将如何将数据反序列化为单独的类?
【问题讨论】:
-
您可以使用
for(testClass item : hSet) { ... }遍历集合
标签: java serialization deserialization hashset