我问了一个先前的问题,关于如何将多个保存文件保存到.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 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();
}
}
}
}
但是我在获取代码来编写带有index(i)的对象时遇到了麻烦,因为它说未为type定义该方法HashSet。有没有一种方法可以遍历哈希集中的每条信息,还是应该一次序列化整个集合。另一个问题是,如果第一个答案是后者,我将如何将数据反序列化为单独的类?