为了账号安全,请及时绑定邮箱和手机立即绑定

数组列表的重复条目

数组列表的重复条目

一只斗牛犬 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 关注
  • 139 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信