这是我昨天发布的一个问题(链接)的延续,因为我很高兴 - 毫无疑问它解决了一个障碍。
按照建议,我删除了静态修饰符。这确实解决了记录累积更改的问题。但是,当我从为问题调试而构建的简化应用程序返回到原始环境时,我注意到添加记录仍然会导致修改之前的记录。我认为我对 ArrayList 做的事情有问题。
我通过删除所有static、final和synchronized修饰符(不管它与问题的相关性如何)简化了应用程序,但仍然存在问题。
我将问题缩小到下面带来的add方法。该方法由数据存储库的构造函数调用,测试记录具有递增的 ID 字段和其他字段的各种值。
private ArrayList<taskDef> tasksTable = new ArrayList<taskDef>();
public void addTask (taskDef newRecord)
{ // Add the record at the array's end
Boolean f = tasksTable.add(newRecord);
System.out.println( "\n>************** storing record (index " + (getTasksTableLength () - 1) +
")\tProject: " + tasksTable.get(getTasksTableLength () - 1).getProjectNumber() +
"\tID: " + tasksTable.get(getTasksTableLength () - 1).getId() +
"\ttable size: " + getTasksTableLength () + "\tsuccess: " + f +
"\tLog: " + tasksTable.get(getTasksTableLength () - 1).getLog());
if (getTasksTableLength () > 1)
System.out.println( ">************** Previous record (index " + (getTasksTableLength () - 2) + "): " +
"\tProject: " + tasksTable.get(getTasksTableLength () - 2).getProjectNumber() +
"\tID: " + tasksTable.get(getTasksTableLength () - 2).getId() +
"\tLog: " + tasksTable.get(getTasksTableLength () - 2).getLog());
}
在日志中,我们可以看到,每当添加记录时,先前的任务都会更改。下面的打印输出只显示了一个以前的记录,但实际上所有以前的记录都在被修改
>************** storing record (index 0) Project: P1000 ID: 1 table size: 1 success: true Log:
11/07/2012 07:14:02: ; project number (P1000); task (Task 1); task ID (1); owner (O1); status (started)
>************** storing record (index 1) Project: P1000 ID: 2 table size: 2 success: true Log:
11/07/2012 07:14:41: ; task (Task 2); task ID (2); delivery flag (true)
>************** Previous record (index 0): Project: P1000 ID: 1 Log:
11/07/2012 07:14:41: ; task (Task 2); task ID (2); delivery flag (true)
>************** storing record (index 2) Project: P1000 ID: 3 table size: 3 success: true Log:
11/07/2012 07:16:08: ; task (Task 3); task ID (3); owner (O2)
>************** Previous record (index 1): Project: P1000 ID: 2 Log:
11/07/2012 07:16:08: ; task (Task 3); task ID (3); owner (O2)