序列化集合时出现ClassCastException

时间:2017-06-08 19:44:53

标签: java serialization classcastexception objectinputstream objectoutputstream

你能帮忙吗?我在因特网上看到了几个例子,他们将它们转发到ArrayList。在这里,我尝试反序列化我的Account类对象的HashMap。我尝试读取整个集合但得到ClassCastException。起初我想只将Account对象写入.ser文件,但它总是覆盖以前保存的帐户,这就是我编写和阅读整个集合的原因。如果这种方法很好,请帮助我找到错误,如果我正在做的是愚蠢的建议其他解决方案,因为我是初学者。 是的,Account实现了java.io.Serializable

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

0 个答案:

没有答案