我编写了一个函数来在两个数组之间插入步骤,但是直到插值完成后才知道所需的步骤数。
这是我的功能:
int[][] interpolate(int[] source, int[] goal){
int[] current = new int[source.length];
ArrayList<int[]> steps = new ArrayList<int[]>();
while(/* condition */){
// Change value of current
steps.add(current);
}
int[][] stepsArr = steps.toArray(new int[0][0]);
return stepsArr;
}
我尝试使用 ArrayList 来存储生成状态,但发现 ArrayList 仅存储指针,因此最终的 ArrayList 包含指向同一对象的多个指针(当前的最终值)。
有什么方法可以动态生成 int[] 实例来存储步骤,或者以其他方式生成整数的二维数组?
最佳答案
您的问题与您对原始类型的使用无关,而是与您对数组的处理有关。通过添加当前
数组的副本来修复您的代码,它将正常工作:
steps.add(Arrays.copyOf(current));
关于java - 动态生成基元并将其存储在 ArrayList 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25545473/