【问题标题】:Generate and store primitives in ArrayList dynamically在 ArrayList 中动态生成和存储基元
【发布时间】:2014-08-28 09:35:16
【问题描述】:

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

这是我的功能:

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 包含指向同一对象的多个指针(current 的最终值)。

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

【问题讨论】:

    标签: java arraylist


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      您总是存储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;
      }
      

      【讨论】:

      • 这破坏了代码:OP 迭代地将插值应用于同一个数组。您需要前一个数组的副本。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-21
      • 2011-12-09
      • 1970-01-01
      • 1970-01-01
      • 2012-04-05
      • 2021-08-19
      相关资源
      最近更新 更多