数组列表中的对象在加载后也相似。为什么?

问题描述 投票:1回答:1

我的程序是一个简单的聊天室。通过注册部分中的文本字段向用户写入的值并创建一个帐户。我有一个名为``Account''的类,该类在输入中采用相同的值,并且包含相同的字段。需要保存并加载所有帐户,以供以后实施。我使用了下面的代码(这是程序代码的一部分),但是存在问题。加载后我打印了这些值,发现它报告的是空值。然后在将新帐户添加到数组列表后,列表中的所有值都将更改为添加的值。例如,我创建并保存一个名为“ a”的帐户并发送电子邮件“ a”,然后再次运行该程序。在此处添加名称和电子邮件“ B”的帐户会打印两个帐户B。出了什么问题?

String email= t4.getText();
String password=t5.getText();
String name=t1.getText();
String family=t2.getText();
String phoneNumber=t3.getText();
try {
    FileInputStream f = new FileInputStream("accounts.txt");
    ObjectInputStream obj = new ObjectInputStream(f);
    int size=obj.readInt();
    for (int i = 0; i <size ; i++) {
        accounts.add((Account)obj.readObject());
    }
} catch (Exception e){
    e.printStackTrace();
}
for (int i = 0; i <accounts.size() ; i++) {
    System.out.println(accounts.get(i).name+"  "+accounts.get(i).email);
}
Account account = new Account(name,family,phoneNumber,email,password);
accounts.add(account);
try{
    FileOutputStream f=new FileOutputStream("accounts.txt",false);
    ObjectOutputStream obj=new ObjectOutputStream(f);
    obj.writeInt(accounts.size());
    for (Account a:accounts) {
        obj.writeObject(a);
    }
} catch (Exception e){
     e.printStackTrace();
}
for (int i = 0; i <accounts.size() ; i++) {
    System.out.println(accounts.get(i).name+"  "+accounts.get(i).email);
}
//class account
class Account implements Serializable {
    static String name, family, phoneNumber, email, password;
    static ArrayList<Post> posts = new ArrayList();
    static ArrayList<Account> following = new ArrayList();
    static ArrayList<Account> follower = new ArrayList();

    Account(String n, String f, String pn, String e, String ps) {
        name = n;
        family = f;
        phoneNumber = pn;
        email = e;
        password = ps;
    }

    void follow(Account user) {
        following.add(user);
        user.follower.add(this);
    }

    void post(String data) {
        Post post = new Post(data, new Date(), this);
        posts.add(post);
        for (Account account : follower) {
            account.posts.add(post);
        }
    }
}
java arraylist inputstream objectinputstream
1个回答
1
投票

Account类的所有成员都是static,这意味着它们属于class而不是特定的instance。使它们成为非静态的,您应该可以使用。

© www.soinside.com 2019 - 2024. All rights reserved.