英文:
The list is not filled
问题
你尝试将数据嵌套到一个列表中,然后将该列表添加到另一个列表中。挑战在于获得一组嵌套的数据列表。
String content1;
String content2;
ArrayList<ArrayList<String>> listData = new ArrayList<>();
ArrayList<String> listDataOne = new ArrayList<>();
for (int i = 0; i < 3; i++) {
content1 = "one " + i;
content2 = "two " + i;
listDataOne.add(content1);
listDataOne.add(content2);
System.out.println(listDataOne);
listData.add(listDataOne);
System.out.println(listData); // [[one 2, two 2], [one 2, two 2], [one 2, two 2]]
listDataOne.clear();
}
System.out.println(listData); // [[], [], []]
但最后,你得到了空的嵌套列表。我做错了什么?
英文:
I am trying to nest data into a list, which I also add to another list. The challenge is to get a list of nested lists of data.
String content1;
String content2;
ArrayList<ArrayList<String>> listData = new ArrayList<>();
ArrayList<String> listDataOne = new ArrayList<>();
for (int i = 0; i < 3; i++) {
content1 = "one " + i;
content2 = "two " + i;
listDataOne.add(content1);
listDataOne.add(content2);
System.out.println(listDataOne);
listData.add(listDataOne);
System.out.println(listData); // [[one 2, two 2], [one 2, two 2], [one 2, two 2]]
listDataOne.clear();
}
System.out.println(listData); // [[], [], []]
But in the end, I get empty nested lists. What am I doing wrong?
答案1
得分: 2
在你的for
循环结束时,你清空了listDataOne
,由于listData
引用相同的列表,它也被清空了。你需要将
listDataOne.clear();
替换为
listDataOne = new ArrayList<>();
以保留数据。
英文:
At the end of your for
loop you're clearing listDataOne
and since listData
has the same list reference, it gets cleared too. You need to replace
listDataOne.clear();
with
listDataOne = new ArrayList<>();
to preserve data.
答案2
得分: 0
这是翻译好的部分:
"这是因为 listData
存储的是对 listDataOne
的引用,而不是值。因此,当您清除引用时,将没有值,当您更新 listDataOne
时,所有对它的引用都将被更新。
String content1;
String content2;
ArrayList<ArrayList<String>> listData = new ArrayList<>();
ArrayList<String> listDataOne;
for (int i = 0; i < 3; i++) {
listDataOne = new ArrayList<>();
content1 = "one " + i;
content2 = "two " + i;
listDataOne.add(content1);
listDataOne.add(content2);
System.out.println(listDataOne);
listData.add(listDataOne);
System.out.println(listData);
}
System.out.println(listData);
您还应该阅读此帖子。"
英文:
It's happing because listData
is storing reference of listDataOne
instead of value. So, when you clear the reference will have no value and when you update listDataOne
all the reference to it will be updated.
String content1;
String content2;
ArrayList<ArrayList<String>> listData = new ArrayList<>();
ArrayList<String> listDataOne;
for (int i = 0; i < 3; i++) {
listDataOne = new ArrayList<>();
content1 = "one " + i;
content2 = "two " + i;
listDataOne.add(content1);
listDataOne.add(content2);
System.out.println(listDataOne);
listData.add(listDataOne);
System.out.println(listData);
}
System.out.println(listData);
You should also go through this this post.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论