有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

数组列表的java重复项

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

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

共 (2) 个答案

  1. # 1 楼答案

    由于clear()会影响已添加到最终结果(在上一次迭代中)的列表,因此必须在清除它(2)之前复制(1)

    list.add(new ArrayList<>(temp));  // 1
    temp.clear();                     // 2
    

    让我们从^{中移出3个重复的行

    switch (q) {
        case 1:
            temp.add("case1");
            break;
    
        case 2:
            temp.add("case2");
            break;
    }
    methodA();
    list.add(new ArrayList<>(temp));
    temp.clear();
    
  2. # 2 楼答案

    之所以会发生这种情况,是因为您正在将完整的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;
            }
        }