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.