3 回答

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;
}
}

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();

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;
}
}
添加回答
舉報