我有这个:

      byte[] AllNumber = {4,3,2,1,0,5,6,7,8,9};
      byte[] MultNumber = {4,3,2,1,0,5,6,7,8,9}; // No matter the content
      byte[] DivNumber = {4,3,2,1,0,5,6,7,8,9}; // No matter the content

      Alter(AllNumber,MultNumber,DivNumber,5.0,3,2); //The Arrays must be Altered!!

      for (int i = 0; i<MultNumber.length; i++) {
        System.out.println("MultNumber["+i+"]:"+MultNumber[i]);
      }
      for (int i = 0; i<DivNumber.length; i++) {
        System.out.println("DivNumber["+i+"]:"+DivNumber[i]);
      }


现在我有了这个方法:

      Alter(byte[] src, byte[] Mlt, byte[] Dvs, double dNum, int Lngt, int Ini) {
        // INI THE PROBLEM
        Mlt = Arrays.copyOf(Mlt, src.length + Lngt);  //HERE IS THE ASSIGNATION
        for (int i = ini; i<Mlt.length; i++) {
          Mlt[i] = Mlt[i]*dNum; //No matter the operation (to simplify the problem)
        }

        Dvs = Arrays.copyOf(Dvs, src.length - Lngt);  //HERE IS THE ASSIGNATION
        for (int i = Ini; i<Dvs.length; i++) {
          Dvs[i] = Dvs[i]/dNum; //No matter the operation (to simplify the problem)
        }
        // END THE PROBLEM
      }


另一尝试

      //Another Attempt!!!
      Alter(byte[] src, byte[] Mlt, byte[] Dvs, double dNum, int Lngt, int Ini) {
        // INI THE PROBLEM
        byte[] TM = new byte[src.length + Lngt]
        for (int i = ini; i<Mlt.length; i++) {
          TM[i] = Mlt[i]*dNum; //No matter the operation (to simplify the problem)
        }
        Mlt = TM;  //HERE IS THE ASSIGNATION
        TM = null;

        byte[] TD = new byte[src.length - Lngt]
        for (int i = Ini; i<Dvs.length; i++) {
          TD[i] = Dvs[i]/dNum; //No matter the operation (to simplify the problem)
        }
        Dvs = TD;  //HERE IS THE ASSIGNATION
        TD = null;
        // END THE PROBLEM
      }


在执行方法“ Alter”的调用后,我想更改两个安排。
我该怎么做?

我需要更改数组的长度!

感谢您的宝贵帮助。

PD。似乎稍后要对数组进行分配,“按引用调用”将转换为“按值调用”。如果省略了“分配”,则会出现“按引用调用”。

最佳答案

我需要更改数组的长度!


在Java中这是不可能的。您可以使用动态数据结构,例如java.util.List接口的实现。

您的分配没有帮助,因为方法参数是引用原始对象的局部变量。因此,您的对象有两个引用,并且您只更改了方法内部已知的引用。

Java使用按值调用,对于引用数据类型,该值是引用的值(因此您获得对同一对象的引用)。

当您想更改数组时,可以执行以下操作。

public static int[] arrayTwiceAsBig(int[] original) {
    int[] newOne = new int[original.length * 2);
    System.arraycopy(original, 0, newOne, 0, original.length);
    return newOne;
}


并这样称呼它:

int[] myArray = {1,2,3};
myArray = arrayTwiceAsBig(myArray);
System.out.println(Arrays.toString(myArray));

10-02 02:29
查看更多