3 回答
![?](http://img1.sycdn.imooc.com/5333a207000118af02200220-100-100.jpg)
TA贡献2021条经验 获得超8个赞
您必须在每个循环中清除临时列表或重新设置它。我个人更喜欢选项2。
ArrayList<String> temp = new ArrayList<>();
public static void main(String[] args) {
for (int q = 1; q < 3; q++) {
temp = new ArrayList<>();
switch (q) {
case 1:
temp.add("case1");
methodA();
list.add(temp);
break;
case 2:
temp.add("case2");
methodA();
list.add(temp);
break;
}
}
![?](http://img1.sycdn.imooc.com/5333a1a90001c8d802000200-100-100.jpg)
TA贡献1785条经验 获得超8个赞
由于clear()影响已添加到最终结果的列表(在前一次迭代中),您必须在清除它之前制作副本 (1) (2)。
list.add(new ArrayList<>(temp)); // 1
temp.clear(); // 2
让我们将 3 个重复的行移出switch.
switch (q) {
case 1:
temp.add("case1");
break;
case 2:
temp.add("case2");
break;
}
methodA();
list.add(new ArrayList<>(temp));
temp.clear();
![?](http://img1.sycdn.imooc.com/5333a1660001394602000200-100-100.jpg)
TA贡献1862条经验 获得超6个赞
发生这种情况是因为您将完整的 Arraylist 添加到字符串列表中而不清除它。你可以做的是在每个 case 语句中清除 arrayList temp
for (int q = 1; q < 3; q++) {
switch (q) {
case 1:
temp = new ArrayList<>();
temp.add("case1");
methodA();
list.add(temp);
break;
case 2:
temp = new ArrayList<>();
temp.add("case2");
methodA();
list.add(temp);
break;
}
}
添加回答
举报