-1

I am trying to save a list of permutations to use later in my program. However, when I try to append the permutation results to full_list, the original list gets saved to the list over and over. BUT the results printed from System.out.println(arr); are exactly what I want.

import java.util.*;

public class mytest {

    public static void main(String[] args){
        ArrayList<Integer> inlist = new ArrayList<Integer>();
        inlist.add(1);
        inlist.add(2);
        inlist.add(3);
        permute(inlist, 0);
        System.out.println(full_list);
    }

    public static HashSet<ArrayList<Integer>> full_list = new HashSet<ArrayList<Integer>>();

    public static void permute(ArrayList<Integer> arr, int k){

        for(int i = k; i < arr.size(); i++){
            java.util.Collections.swap(arr, i, k);
            permute(arr, k+1);
            java.util.Collections.swap(arr, k, i);
        }
        if (k == arr.size() -1){
            System.out.println(arr);
            full_list.add(arr);
        }
    }
}

results from System.out.println(arr);

[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 2, 1]
[3, 1, 2]

results from printing full_list in the main method:

[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]

What can I do to fix this so the printed results are saved in the full_list?

daedsidog
  • 1,732
  • 2
  • 17
  • 36
delonay
  • 29
  • 1
  • 3

2 Answers2

2

You are changing values of arr that are adding to full_list. To prevent this you should add new clone of arr to full_list:

full_list.add(new ArrayList<>(arr));
Mohsen
  • 4,536
  • 2
  • 27
  • 49
0

Just do: full_list.add(new ArrayList<Integer>(arr));

The error in your code is that you are adding the same ArrayList every time, but you have to create a copy of it. This code is creating a copy new ArrayList<Integer>(arr)

Sergei Sirik
  • 1,249
  • 1
  • 13
  • 28