简体   繁体   English

阵列的ArrayList每次都会被覆盖

[英]ArrayList of Arrays gets overwritten everytime

I'm trying to use ArrayList in a recursive function. 我正在尝试在递归函数中使用ArrayList。 I'm trying to find the combinations of the array arr of size r. 我试图找到大小r的数组arr的组合。 Like if I have an array 就像我有一个数组

["A","B","C","D"]

I want to print : 我要打印:

A B C
A B D
A C D
B C D

But when I print my ArrayList in the recursive function it gives: 但是,当我在递归函数中打印ArrayList时,它给出了:

Call1 : ABC
Call2 : ABD
        ABD

And so on. 等等。 ie every time the previous contents of the ArrayList are overwritten with the new content and the new content is also added to the end. 即,每次ArrayList的先前内容被新内容覆盖,并且新内容也添加到末尾。 Also in the Function calling the recursive function my ArrayList is not returned it just contains a list of Es. 同样在调用递归函数的函数中,未返回我的ArrayList,它仅包含Es列表。

In the function calling the recursive function I have something like 在调用递归函数的函数中,我有类似

private static void combine(String[] arr, int r) {
    String[] res = new String[r];
    ArrayList<String[]> result = new ArrayList<String[]>();
    doCombine(arr, res, 0, 0, r, result);
    System.out.println("\nIn main" + result.size());
    for (Object[] array : result) {
        for (Object o : array)
            System.out.print("item: " + o);
        System.out.println();
    }
}

// This recursive function finds combinations
private static void doCombine(String[] arr, String[] res, int currIndex,
  int level, int r, ArrayList<String[]> result) {

    if (level == r) {
        printArray(res);
        String[] inter = new String[r];
        inter = res;
        result.add(inter);
        // Tryinh to see wht the array list has every time
        for (Object[] array : result) {
            for (Object o : array) {
                System.out.print("item: " + o);
            }
            System.out.println();
        }
        inter = null;
        return;
    }
    for (int i = currIndex; i < arr.length; i++) {
        counter.add();
        res[level] = arr[i];
        doCombine(arr, res, i + 1, level + 1, r, result);
    }
}

Please tell me what I am doing wrong. 请告诉我我在做什么错。

Modify the code 修改代码

    String[] inter = new String[r];
    inter = res;
    result.add(inter);

to

        String[] inter = new String[r];
        int k=0;
        for(String s:res){
            inter[k] = s;
            k++;
        }
        result.add(inter);

And the code work as Expected. 并且代码按预期工作。

Output: 输出:

1 1

ABC ABC

2 2

ABC ABC

ABD ABD

3 3

ABC ABC

ABD ABD

ACD ACD

4 4

ABC ABC

ABD ABD

ACD ACD

BCD BCD

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM