while 循环外的 ArrayList 未更新

ArrayList outside while loop isn't being updated

无论我尝试什么,方法中的 ArrayList<int[]> 都默认为相同的值。使用 System.out.println()s,我能够发现我的方法中的 while 循环对 ArrayList 进行了更改,但是一旦它退出循环,它总是默认为数组 [0,1,2] .

方法如下:

private int[][] computeHighestSum() {
    int totalValue = Integer.MIN_VALUE;
    ArrayList<int[]> lowestPositions = new ArrayList<int[]>(); //creates list to hold sequences
    totalValue = (int) graphTraversal(positions)[0]; //assigns default sequence's value
    lowestPositions.add(positions); //adds default sequence to the List

    Object[] x; 
    //loops through and tries other sequences
    while((x = graphTraversal())[1] != null) {
        //if the current sequence produces greater value, clear the List, and then add this sequence, and assign new value to totalValue
        if((int) x[0] > totalValue) {
            lowestPositions.clear();
            totalValue = (int) x[0];
            lowestPositions.add((int[]) x[1]);

        } else if((int) x[0] == totalValue) { 
            lowestPositions.add((int[]) x[1]);
        }
    }
    return lowestPositions.toArray(new int[lowestPositions.size()][]);
}

该方法的作用是首先遍历一个图并计算出一个总值,并将其设置为默认值totalValue。然后它将特定的图形导航序列添加到 ArrayList<int[]>,其中包含 int[] 中的导航序列。这成为默认的 totalValue 和图形序列。

然后它使用不同的序列遍历同一个图,直到用完有效序列。如果它找到一个大于当前 totalValue 的值,它会将该值分配给 totalValue,并清除 ArrayList,然后添加新序列。如果发现相同,则将其添加到 ArrayList

while 循环中,它进行了更改和所有操作,但是方法一结束,ArrayList 始终包含相同的数组。有趣的是,如果 while 循环找到 n 个相同的 totalValue ,它会将它们全部添加到 ArrayList 但在方法结束时, ArrayList 中的所有 n 元素都是同一个数组:[0,1,2].

即使我去掉了开头的lowestPositions.add(positions);,它在开头添加了[0,1,2],它仍然默认为它在最后。 totalValue 总是计算正确。

这是我的 System.out.println() 调试代码,如果有帮助的话:

 private int[][] computeHighestSum() {
    int totalValue = Integer.MIN_VALUE;
    ArrayList<int[]> lowestPositions = new ArrayList<int[]>();
    totalValue = (int) graphTraversal(positions)[0];
    lowestPositions.add(positions);
    System.out.println("Default Array added: " + Arrays.toString(positions));
    Object[] x;
    while((x = graphTraversal())[1] != null) {
        System.out.println(Arrays.toString((int [])x[1]));
        if((int) x[0] > totalValue) {
            lowestPositions.clear();
            totalValue = (int) x[0];
            lowestPositions.add((int[]) x[1]);
            System.out.println("An Array Greater Added: " + Arrays.toString((int[]) x[1]));
            System.out.println(Arrays.toString(lowestPositions.get(0)));
        } else if((int) x[0] == totalValue) {
            System.out.println("An Array Equal Added: " + Arrays.toString((int[]) x[1]));
            lowestPositions.add((int[]) x[1]);
        }
    }
    System.out.println(Arrays.toString(lowestPositions.get(0)));
    System.out.println(lowestPositions.size());
    System.out.println(totalValue);
    return lowestPositions.toArray(new int[lowestPositions.size()][]);
}

这是一些示例输出(我现在从终端输入矩阵的值):

方法 private int[] getNextPositions() returns 始终引用同一个数组: int[] tempArray = positions;

这似乎是问题的根源。