1

我在 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.
4

1 回答 1

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));
于 2013-08-27T16:20:13.067 回答