If, and only if, all of the elements of a HashSet are Serializable, HashSet can be saved to an
ObjectOutputStream and later read it in to an ObjectInputStream.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class MainClass {
public static void main(String[] a) throws Exception{
String elements[] = { "A", "B", "C", "D", "E" };
Set set = new HashSet(Arrays.asList(elements));
FileOutputStream fos = new FileOutputStream("set.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(set);
oos.close();
FileInputStream fis = new FileInputStream("set.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Set anotherSet = (Set) ois.readObject();
ois.close();
System.out.println(anotherSet);
}
}
[D, A, C, B, E]