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?