public class Database {
private HashSet<Account> database;
private Iterator<Account> it;
private String fileName;
public Database(String fname)
{
this.fileName = fname;
try (ObjectInputStream db = new ObjectInputStream(new FileInputStream(fileName)))
{
try
{
database = (HashSet<Account>) db.readObject();
}
catch (ClassNotFoundException ex)
{
System.out.println(ex);
}
}
catch (FileNotFoundException ex)
{
System.out.println(fileName + " file not found");
}
catch (IOException ex)
{
System.out.println("IOException in constructor during serialization. File may be empty.");
}
}
public void addNewAccount(String username, String password, float cash) throws UsernameExistsException
{
Account newAcc = new Account(username, password, cash);
if (approveAccount(username))
{
// If account already exists we can't create it with the same username (password can repeat)
throw new UsernameExistsException();
}
else
{
try (ObjectOutputStream db = new ObjectOutputStream(new FileOutputStream(fileName)))
{
database.add(newAcc); // Add new account to current read set database
db.writeObject(database);
}
catch (IOException ex)
{
System.out.println(ex.toString() + " database.ser - File Not Found, Write operation imposible");
}
}
}
}
OUTPUT:
Exception in thread "main" java.lang.ClassCastException: Database.Account cannot be cast to java.util.HashSet
at Database.Database.<init>(Database.java:22)
at Shop.Main.main(Main.java:21)
C:\Users\Sak\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1