亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

數組列表的重復條目

數組列表的重復條目

一只斗牛犬 2021-06-14 16:08:40
我想為新項目創建一個新列表,而不是將新項目添加到現有列表中。例如,FINAL OUTPUT:[[case1, this is method A], [case2, this is method A]]但是,我的代碼輸出是FINAL OUTPUT:[[case1, this is method A, case2, this is method A], [case1, this is method A, case2, this is method A]]我不太確定我哪里出錯了。任何幫助表示贊賞!謝謝!下面是我的代碼。   static List<List<String>> list = new ArrayList<>();    static ArrayList<String> temp = new ArrayList<>();    public static void main(String[] args) {        for (int q = 1; q < 3; q++) {            switch (q) {            case 1:                temp.add("case1");                methodA();                list.add(temp);                break;            case 2:                temp.add("case2");                methodA();                list.add(temp);                break;            }        }        System.out.println("FINAL OUTPUT:" + list);    }    private static void methodA() {        temp.add("this is method A");    } 
查看完整描述

3 回答

?
寶慕林4294392

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;

            }

        }


查看完整回答
反對 回復 2021-06-17
?
慕的地10843

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


查看完整回答
反對 回復 2021-06-17
?
阿波羅的戰車

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;

        }

    }


查看完整回答
反對 回復 2021-06-17
  • 3 回答
  • 0 關注
  • 196 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號