ArrayList 未显示正确大小的问题
所以我得到了这段代码,如果 ArrayList 不存在,它将把数字 1-9 添加到单独的 ArrayList 中。然而,即使我打印了 ArrayLists(并且它得到了所有正确的数字),当我打印 ArrayList 的 .size 时,它给了我 1 而不是 9。我希望你理解我的问题。这是代码:
ArrayList[][] tillatnaSiffror = new ArrayList[9][9];
for(int i=0;i<9;i++){
for(int ruta=0;ruta<9;ruta++){
if(tillatnaSiffror[i][ruta] == null){
for(int add=1;add<=9;add++){
tillatnaSiffror[i][ruta] = new ArrayList<Integer>();
tillatnaSiffror[i][ruta].add(add);
System.out.println(tillatnaSiffror[i][ruta]);
}
System.out.println(tillatnaSiffror[i][ruta].size());
}
}
}
这给了我这个(当然虽然九次):[1][2][3][4][5][6][7][8][9]1
现在我想知道,为什么当我打印 .size 时得到 1 而不是 9?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因为您在每次迭代中重置列表
,即创建一个新列表,为添加的每个数字丢弃前一个列表!
尝试移出列表的创建:
Ideone.com demo
作为旁注,我建议在这里避免使用数组,而完全使用 Java 集合。例如,考虑使用像
List
这样的结构。>>
Because you reset the list in each iteration by doing
i.e., you create a new list, throwing away the previous one for each digit you add!
Try moving out the creation of the list:
Ideone.com demo
As a side note, I would suggest to avoid arrays here, and use Java collections all the way. Consider for instance to use a structure like
List<List<Set<Integer>>>
.