二维ArrayList不断添加新值

时间:2013-08-27 16:17:27

标签: java performance arraylist

我在Java中发现了使用二维ArrayLists的以下行为:

ArrayList<ArrayList<Date>> parentList = new ArrayList<ArrayList<Date>>();
ArrayList<Date> childList = new ArrayList<Date>();

//Adding a date to childList
childList.add(date1);

//Adding a 'row' to parentList
parentList.add(childList);

//Adding another date to childList
childList.add(date2);

//Adding another row to parentList
parentList.add(childList);

System.out.println(parentList.get(0));
System.out.println(parentList.get(1));

//Expected output:   
//   [date1]
//   [date1, date2]

//Real output:   
//   [date1, date2]
//   [date1, date2]

所以看来,尽管将childList添加到parentList,但是新添加到childList的项目也立即被添加到parentList中。

我想出了以下针对此问题的解决方案:

ArrayList<ArrayList<Date>> parentList = new ArrayList<ArrayList<Date>>();
ArrayList<Date> childList = new ArrayList<Date>();
ArrayList<Date> cacheList = new ArrayList<Date>();

//Adding a date to childList
childList.add(date1);

//Adding a 'row' to parentList
parentList.add(childList);

//Saving all current dates in cacheList
cacheList = childList;
childList = new ArrayList<Date>();

for (int i = 0; i < cacheList.size(); i++)
{
    childList.add(cacheList.get(i));
}

cacheList = new ArrayList<Date>();

//Adding another date to childList
childList.add(date2);

//Adding another row to parentList
parentList.add(childList);

System.out.println(parentList.get(0));
System.out.println(parentList.get(1));

//Expected output:   
//   [date1]
//   [date1, date2]

//Real output:   
//   [date1]
//   [date1, date2]

但我发现这个解决方案有点多余和丑陋。

所以我想知道:这个问题有更优雅的解决方案吗?

编辑:请注意,我需要childList累积。所以它应该包含所有元素,但每次添加一个元素,然后它就会存储在parentList中。

例如:

for (int i = 0; i < parentList.size(); i++)
{
     System.out.println(parentList.get(i));
}

应输出如下内容:

[date1]
[date1, date2]
[date1, date2, date3]
[date1, date2, date3, date4]
etc.

1 个答案:

答案 0 :(得分:3)

您要添加两次相同的childList实例。所有操作都在该对象上完成。由于您添加了两次,所以一切都给人以两次发生的印象。要解决此问题,请添加childList的副本,如下所示:

ArrayList<ArrayList<Date>> parentList = new ArrayList<ArrayList<Date>>();
ArrayList<Date> childList = new ArrayList<Date>();

//Adding a date to childList
childList.add(date1);

//Adding a 'row' to parentList
parentList.add(new ArrayList<Date>(childList)); // COPY!

//Adding another date to childList
childList.add(date2);

//Adding another row to parentList
parentList.add(new ArrayList<Date>(childList)); // COPY!

System.out.println(parentList.get(0));
System.out.println(parentList.get(1));