Java:如何从方法内部更改Integer数组参数

问题描述 投票:0回答:2

我有一个编程任务,我必须创建一个方法,接受一个分成子数组的数组,并合并它们。我的方法工作正常,但在'a'中传递的Integer数组只从方法内部更改,并且从外部保持不变。

在浏览谷歌后,我得出结论,无法更改数组参数,但后来我想到了Arrays.sort,它最终会从方法外部更改数组参数。

如何更改作为参数传入的数组,以便它在方法之外保持更改?

    /**
        * Merge three sorted arrays with these ranges [lo..mid1], [mid1+1..mid2], [mid2+1..hi] into one sorted array.
        * Array a has the original input and final sorted input. 
        * Array aux is the auxiliary array.
        */

   public static void Merge(Integer[] a, int lo, int mid1, int mid2, int hi, Integer[] aux) {

      int[] arr1 = copyArray(a, lo, mid1);
      int[] arr2 = copyArray(a, mid1+1, mid2);
      int[] arr3 = copyArray(a, mid2+1, hi);

      int i = 0, j = 0, k = 0, idx = 0;

      while(i < arr1.length-1 || j < arr2.length-1 || k < arr3.length-1) {

         // arr1[i] is the smallest
         if(arr1[i] <= arr2[j] && arr1[i] <= arr3[k]) {
            System.out.println("i is bigger at " + arr1[i]);
            aux[idx] = arr1[i];
            i++;
         }

         // arr2[j] is the smallest
         else if(arr2[j] <= arr1[i] && arr2[j] <= arr3[k]) {
         System.out.println("j is bigger at " + arr2[j]);
            aux[idx] = arr2[j];
            j++;
         }

         // arr3[k] is the smallest
         else if(arr3[k] <= arr2[j] && arr3[k] <= arr1[i]) {
            System.out.println("k is bigger at " + arr3[k]);
            aux[idx] = arr3[k];
            k++;
         }

         idx++;
      }


      System.out.println(Arrays.toString(arr1));
      System.out.println(Arrays.toString(arr2));
      System.out.println(Arrays.toString(arr3));


      System.out.println(Arrays.toString(aux));

      a = aux;
      a[0] = 900;
      System.out.println("a from Merge method: " + Arrays.toString(a));


   }
java arrays parameter-passing
2个回答
1
投票

你必须迭代你的aux数组并将值赋给'a'数组:

a[i] = aux[i]

或者返回合并后的数组作为结果。

public static int[] Merge(int[] a, int mid1, ...){
   // do something
  return a;
}

0
投票

您可以将void更改为int [] [],然后返回数组

public static int[][] Merge(arguments) {
    //Do math
    int[][] result = new int[][] {arr1, arr2, arr3};
    return result;
}

然后,在方法之外,您可以调用它,如下所示:

int[][] integerArray = Merge(arguments);
arr1 = integerArray[0];
arr2 = integerArray[1];
arr3 = integerArray[2];
© www.soinside.com 2019 - 2024. All rights reserved.