添加记录时会修改ArrayList成员

时间:2012-07-11 04:56:22

标签: java arraylist

这是我昨天发布的一个问题(a link)的延续,因为我很高兴 - 无疑它解决了障碍。

根据建议我删除了静态修饰符。这确实解决了记录累积变化的问题。但是,当我从为问题调试而构建的简化应用程序返回到原始环境时,我注意到添加记录仍然会导致修改以前的记录。我认为我使用ArrayList做错了。

我通过删除所有静态最终同步修饰符(无论其与问题的相关性)来简化应用程序,并且仍然具有问题。

我将问题缩小到下面提到的添加方法。该方法由数据存储库的构造函数调用,测试记录包含增量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)

0 个答案:

没有答案