Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/delphi/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在ArrayList中动态生成和存储原语_Java_Arraylist - Fatal编程技术网

Java 在ArrayList中动态生成和存储原语

Java 在ArrayList中动态生成和存储原语,java,arraylist,Java,Arraylist,我已经编写了一个函数来插值两个数组之间的步长,但是在插值完成之前,所需的步长是未知的 以下是我的功能: int[][] interpolate(int[] source, int[] goal){ int[] current = new int[source.length]; ArrayList<int[]> steps = new ArrayList<int[]>(); while(/* condition */){ // C

我已经编写了一个函数来插值两个数组之间的步长,但是在插值完成之前,所需的步长是未知的

以下是我的功能:

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;
}
int[]interpolate(int[]source,int[]goal){
int[]当前=新int[source.length];
ArrayList步骤=新建ArrayList();
而(/*条件*/){
//电流变化值
步骤。添加(当前);
}
int[]stepsArr=steps.toArray(新的int[0][0]);
返回步骤;
}
我曾尝试在生成状态时使用ArrayList来存储状态,但发现ArrayList只存储指针,因此最终的ArrayList包含指向同一对象的多个指针(current的最终值)


有没有办法动态生成int[]实例以分步存储,或者生成一个二维整数数组?

您的问题与基本类型的使用无关,而是与数组的处理有关。通过添加
当前
数组的副本修复代码,它将正常工作:

steps.add(Arrays.copyOf(current));

您总是在存储当前的相同实例。您可以为每个迭代创建一个新实例

int[][] interpolate(int[] source, int[] goal){

    int[] current;
    ArrayList<int[]> steps = new ArrayList<int[]>();

    while(/* condition */){
        current = new int[source.length];
        // Change value of current

        steps.add(current);
    }
    int[][] stepsArr = steps.toArray(new int[0][0]);
    return stepsArr;
}
int[]interpolate(int[]source,int[]goal){
int[]电流;
ArrayList步骤=新建ArrayList();
而(/*条件*/){
当前=新整数[源.长度];
//电流变化值
步骤。添加(当前);
}
int[]stepsArr=steps.toArray(新的int[0][0]);
返回步骤;
}

这打破了代码:OP迭代地将插值应用于同一数组。您需要上一个数组的副本。