Search code examples
javaarraylistpermutation

ArrayList<ArrayList<Integer> returns same values when adding different elements to it


I need to add List of permutation to ArrayList type but for me when I try to run below code then I am getting same value repeated. Please help me here.

public static void permutation(ArrayList<Integer> perm, ArrayList<ArrayList<Integer>> solution, int index) {
        if (index >= perm.size()) {
            solution.add(perm);
            return;
        }

        for (int i = index; i < perm.size(); i++) {
            Collections.swap(perm, index, i);
            permutation(perm, solution, index + 1);
            Collections.swap(perm, index, i);
        }

    }

if passed [1,2,3] as first argument. Expected output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] should be added to second argument. Actual output: [[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3]]


Solution

  • You need to understand that

    solution.add(perm);
    

    does not add a copy of perm to solution - it only adds a reference to perm. You are changing the contents perm after that line, which means that whatever seems to have been added to solution also changes (because it is the same object).

    What you need to do instead is to add a copy of perm to the solution.

    In your case the simplest way to create such a copy is by creating a new ArrayList<Integer>(perm):

    solution.add(new ArrayList<Integer>(perm));