无论我做什么,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
s,它将所有这些添加到 ArrayList
但在方法结束时,所有 n
ArrayList
内的元素是相同的数组:[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() 始终返回对同一数组的引用:
int[] tempArray = 位置;
这似乎是问题的根源。
关于java - while 循环之外的 ArrayList 未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28936638/