Adding an int Array after modification but ends up adding the old int Array

Viewed 28

I'm writing code to take an int[] and adding all of its permutations to a Collection. The code works and makes the correct swaps. Before adding it to the Stack, I have a print statement showing me my array before adding it:

132
213
231
312
321

But then when I print the arrays in the stack after the permutations are done, I get:

321
321
321
321
321

I have a feeling it has something to do with how Java handles the array and how the int[] is being added but I'm not sure.

Code here:

    public Stack<int[]> perm(int[] labels) {
        Stack<int[]> perm = new Stack<int[]>();

        int[] value = labels;
        Arrays.sort(value);
        int k = labels.length;

        boolean permutationsComplete = false;
        perm.add(value);

        while (!permutationsComplete) {
            
            int i = k - 1;
            while (i > 0 && value[i - 1] >= value[i]) {
                i--;
            }

            if (i < 1) {
                permutationsComplete = true;
                System.out.println();
                for(int[] list : perm) {
                    this.printList(list);
                }
                return perm;
            }

            int j = k;
            while (value[j - 1] <= value[i - 1]) {
                j--;
            }

            int swap1 = value[i - 1];
            value[i - 1] = value[j - 1];
            value[j - 1] = swap1;

            i++;
            j = k;

            while (i < j) {
                int swap2 = value[i - 1];
                value[i - 1] = value[j - 1];
                value[j - 1] = swap2;
                i++;
                j--;
            }
            perm.add(value);
        }
        return null;
    }
1 Answers

Answers were in the comments but basically the way I was trying to copy the arrays to new arrays was assigning different references to the same array object. By replacing:

perm.add(value);

with:

int[] newValue = Arrays.CopyOf(value, value.length);
perm.add(newValue);

I was able to get around this. I'm sure there's a cleaner way to write this code but for now this gets me what I need.

Related