Java 使用arrayList更新文件中的记录

Java 使用arrayList更新文件中的记录,java,file-io,arraylist,Java,File Io,Arraylist,我有一个正在玩游戏的用户列表。他们有一些统计数据,我存储在arrayList newList中。一旦游戏退出,我将把arrayList值存储在一个.dat文件中。现在的问题是我需要更新一个用户的记录,如果我的.dat文件中已经存在这个用户。我想在这里使用3 arrayList 1. ArrayList newList will get the records from the file. 2. ArrayList oldList will then store the replica of ne

我有一个正在玩游戏的用户列表。他们有一些统计数据,我存储在arrayList newList中。一旦游戏退出,我将把arrayList值存储在一个.dat文件中。现在的问题是我需要更新一个用户的记录,如果我的.dat文件中已经存在这个用户。我想在这里使用3 arrayList

1. ArrayList newList will get the records from the file.
2. ArrayList oldList will then store the replica of newList.
3. Game ends. Compare arrayList newList and oldList, and store the updated list in ArrayList users.
4. Store the ArrayList users in a file.

void compare()
    {
        Player obj1=null,obj2=null;
        int newSize = newList.size();   //stores the new records of the users.
        int oldSize = oldList.size();   //stores the old records of the users.
        for(int i=0;i<oldSize;i++)
        {
            for(int j=0;j<newSize;j++)
            {
                obj1=newList.get(i);
                obj2=oldList.get(j);
                if(obj1==obj2)
                {
                    users.add(obj1);
                }
                else
                {
                    users.add(obj2);
                }
            }

        }
    }

//store the records of users in the filename.dat
1。ArrayList newList将从文件中获取记录。
2.ArrayList oldList随后将存储newList的副本。
3.游戏结束。比较arrayList newList和oldList,并将更新后的列表存储在arrayList用户中。
4.将ArrayList用户存储在文件中。
void compare()
{
播放器obj1=null,obj2=null;
int newSize=newList.size();//存储用户的新记录。
int oldSize=oldList.size();//存储用户的旧记录。

对于(inti=0;i,使用普通文件存储“会话数据”可能不是最好的方法,您可能会发现与并发、i/O阻塞等相关的问题

在你的例子中,我会使用一些嵌入式数据库,比如,或者,我在一个类似的场景中使用了H2,它工作得非常好

但是,如果您希望(出于任何原因)自己将数据存储在文件中,那么我建议使用
映射
而不是
列表
,使用用户名作为键或任何其他唯一字段来标识用户,这样您就可以轻松获得用户是否存在

另一方面,您的代码没有太多意义,可能我不太理解您的观点,我会使用类似的代码:

  List<Player> users = new ArrayList<Player>(oldList);

  for(String newUser: newList)
  {
      if (!users.contains(newUser)) {
          users.add(newUser);
      }
  }
List users=newarraylist(oldList);
for(字符串newUser:newList)
{
如果(!users.contains(newUser)){
users.add(newUser);
}
}

以前的代码,获取所有旧用户并添加未包含在旧列表中的新用户,这是您需要的吗?

刚刚测试了它,这似乎不起作用。在Java中,您应该使用
equals
方法来比较对象。您在这里建议了一些非常高级的东西。我只是尝试创建一个基于控制台的小程序我只是一个Java初学者。我认为用
Map
HashMap
)来代替
List
并不是那么“高级”,这将简化您的代码以管理存储的用户。我正在通过列表执行大量操作。将其更改为地图,将意味着我需要大量的重新工作。您能建议一下上述代码的错误吗?这似乎不起作用。好的,但我不明白您试图存储的是什么un
users
list,您的代码有点混乱g、 你能解释一下吗?@MrCoder,请回顾一下我的最新答案,如果它不是你需要的,请从功能的角度进一步解释一下