完成后for循环覆盖数组

For-loop overwriting array once finished

在下面的代码中,我尝试制作一个数组洗牌器。这会将字符数组 (charArray) 打乱 runTimes 指定的次数,并将这些数组中的每一个存储在二维数组 shuffledArrays 中。问题是当程序完成 for 循环时,出于某种原因,它会将所有数组设置为最后添加的数组。

感谢任何帮助,谢谢。

import java.util.Random;

public class Testing {

    public static void main(String[] args) {

        char[] charArray = {'a', 'b', 'c', 'd', 'e', 'f'}; //Array to be shuffled
        int runTimes = 3; //Amount of shuffled arrays to create

        char[][] shuffledArrays = new char[runTimes][charArray.length];;


        for (int x = 0; x != runTimes; x++) {
            shuffledArrays[x] = shuffleArray(charArray);

            System.out.print("IN FOR LOOP: shuffledArrays[" + x + "] = ");
            System.out.println(shuffledArrays[x]);
        }

        System.out.print("OUT OF FOR LOOP: shuffledArrays[0] = ");
        System.out.println(shuffledArrays[0]);

        System.out.print("OUT OF FOR LOOP: shuffledArrays[1] = ");
        System.out.println(shuffledArrays[1]);

        System.out.print("OUT OF FOR LOOP: shuffledArrays[2] = ");
        System.out.println(shuffledArrays[2]);

    }

    private static char[] shuffleArray(char[] array) {
        Random rand = new Random();

        for (int x = 0; x < array.length; x++) {
            int randomIndexToSwap = rand.nextInt(array.length);

            char temp = array[randomIndexToSwap];

            array[randomIndexToSwap] = array[x];

            array[x] = temp;
        }

        return array;

    }

}

正如你总是return SAME 数组最后一个影响所有这些。您需要 return 一份或传递一份,例如:

private static char[] shuffleArray(char[] array) {
    Random rand = new Random();

    for (int x = 0; x < array.length; x++) {
        int randomIndexToSwap = rand.nextInt(array.length);

        char temp = array[randomIndexToSwap];

        array[randomIndexToSwap] = array[x];

        array[x] = temp;
    }

    return Arrays.copyOf(array, array.length);
}

不是更改原始数组,而是需要更改数组的副本,例如

private static char[] shuffleArray(char[] inArray) {
    Random rand = new Random();
    char[] array = inArray.clone();
    for (int x = 0; x < array.length; x++) {
        int randomIndexToSwap = rand.nextInt(array.length);
        char temp = array[randomIndexToSwap];
        array[randomIndexToSwap] = array[x];
        array[x] = temp;
    }
    return array;
}

样本运行:

IN FOR LOOP: shuffledArrays[0] = dcfaeb
IN FOR LOOP: shuffledArrays[1] = edcbaf
IN FOR LOOP: shuffledArrays[2] = bfaced
OUT OF FOR LOOP: shuffledArrays[0] = dcfaeb
OUT OF FOR LOOP: shuffledArrays[1] = edcbaf
OUT OF FOR LOOP: shuffledArrays[2] = bfaced

您观察到同一个数组的三种状态。 for 循环第一次迭代的 System.out.println() 语句打印第一个状态,例如 f, b, c, e, a, d。然后在第二次迭代中再次打乱同一个数组,例如 a, e, b, f, c, d。第三次迭代同上。

现在 shuffledArrays[0]shuffledArrays[1]shuffledArrays[2] 指向同一个数组。