gpt4 book ai didi

java - 二维 ArrayList 不断添加新值

转载 作者:行者123 更新时间:2023-11-29 05:38:48 27 4
gpt4 key购买 nike

我在 Java 中发现了二维 ArrayList 的以下行为:

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.

最佳答案

您正在添加相同的 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));

关于java - 二维 ArrayList 不断添加新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18470722/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com