数组得到了规范化,为什么?

时间:2013-11-26 01:29:20

标签: java arrays normalization

好的,我有两个java-classes:

public class MaximumNormalize {

    public static void display(double z1, double z2) {
       System.out.println("doubles are "+z1+" and "+z2);
    }

    public static void display(double[] zahlen) {
       System.out.println("double-array with length "+zahlen.length+" :");

       for (int i=0; i<zahlen.length; i++) {
           System.out.println("Element "+i+" is "+zahlen[i]);
       }
    }

    public static double maximum (double z1, double z2) {
       if (z1>=z2) return z1;
       else return z2;
    }

    public static double maximum (double[] zahlen) {
       double ret = 0;
       for (int i = 0; i < zahlen.length; i++) {
           if (ret < zahlen[i]) ret = zahlen[i];
       }
       return ret;
    }

    public static void normalize (double z1, double z2, double diff) {
       z1 /= diff;
       z2 /= diff;
    }

    public static void normalize (double[] zahlen, double diff) {
       for (int i = 0; i < zahlen.length; i++) {
           zahlen[i] /= diff;
       }
    }
}


public class TestMaximumNormalize {
    public static void main (String[] args) {
       double[] meineZahlen = {6.5, 7.0, 6., 5.5, 6.5, 7.5};
       double x1 = 10.5;
       double x2 = 9.5;

       System.out.println("before:");
       MaximumNormalize.display(x1, x2);
       MaximumNormalize.display(meineZahlen);

       double maximumEinzeln;
       maximumEinzeln = MaximumNormalize.maximum(x1, x2);
       MaximumNormalize.normalize(x1, x2, maximumEinzeln);

       double maximumVomArray;
       maximumVomArray = MaximumNormalize.maximum(meineZahlen);
       MaximumNormalize.normalize(meineZahlen, maximumVomArray);

       System.out.println();
       System.out.println("after:");
       MaximumNormalize.display(x1, x2);
       MaximumNormalize.display(meineZahlen);
      }
}

为什么双数组存储标准化值?我原以为nothings会发生变化,因为normalize-method是一个空洞。但是,数组接收新值,双精度数不会。

2 个答案:

答案 0 :(得分:5)

normalize (double[] zahlen, double diff)方法中,您传递的是双精度数组,在Java中通过引用传递。因此,如果您在方法中修改它,它将修改原始数组。

答案 1 :(得分:2)

在Java中,所有数组变量都是引用。这些引用在上面的代码中按值传递。如果要对阵列的副本进行操作,则必须明确地制作该副本。