如何使用ArrayList设置器加载对象

我是初学者,已经完成了项目。现在,我成功地序列化了ArrayList中的对象,并且当再次打开程序时,我希望程序加载数据。

但是,当我反序列化时,我使用另一个ArrayList并首先添加对象。然后,将其设置为原始版本。失败了我无法再使用我的方法来调用它们。

I am sure that I serialize the object properly that I can call them using the getters in the NimPlayer when deserializing.

 private void loadData(String fileName) {
 NimModel nimModel = new NimModel();
 ArrayList<NimPlayer> playerList = new ArrayList<NimPlayer>();
    try {
        FileInputStream fis = new FileInputStream(fileName);
        ObjectInputStream ois = new ObjectInputStream(fis);
        for (NimPlayer player : (ArrayList<NimPlayer>)ois.readObject()){
            playerList.add(player); 
        }
        nimModel.setPlayerList(playerList);

     } catch (IOException i) {
        i.printStackTrace();
        return;
     } 
}

Here is part of my NimPlayer class

public class NimPlayer implements Serializable  {

private final String userName;
private String familyName;
private String givenName;

private int gamesPlayed;
private int gamesWon;

public NimPlayer(String userName, String familyName, String givenName) {

    this.userName = userName;
    this.familyName = familyName;
    this.givenName = givenName;
    this.gamesPlayed = 0;
    this.gamesWon = 0;
}
//getter and setters
}

And the getters and setters of ArrayList is in the NimModel:

public class NimModel {

private ArrayList<NimPlayer> playerList = new ArrayList<NimPlayer>();

public ArrayList<NimPlayer> getPlayerList() {
    return new ArrayList<NimPlayer>(playerList);
}

public void setPlayerList(ArrayList<NimPlayer> playerList) {
    this.playerList = playerList;
}
}

任何帮助都受到高度赞赏

参考

Getters and Setters for ArrayLists in Java

Using Getter and Setter for arraylist in java

Getters and Setters for ArrayLists in Java

评论