数组列表的重复条目

用户10022096

我想为新项目创建一个新列表,而不是将新项目添加到现有列表中。例如,

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");
    } 
山猫242

您必须在每个循环中清除临时列表或重新设置它。我个人更喜欢选项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;
            }
        }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章