Java 对对象引用执行 return 之后的增量操作

Java performs the increment operation after return on object references

我有这个代码:

public class counter {
    public static void main(String[] args){
        double[] array = new double[10];
        for(int i=0;i<array.length;i++) array[i] = i;
        printArray(array);
        double result = doSomething(array);
        printArray(array);
    }
    public static void printArray(double[] arr){
        for(double d : arr) System.out.println(d);
    }
    public static double doSomething(double[] array){
        return array[0]++;
    }
}

我了解到,在 return 语句之后,不再执行任何代码,并且 increment++ 会在下一个表达式处递增该值。所以对我来说,数组的第一个元素 array[0] 不应该增加是合乎逻辑的。

但是输出数组是 {1,1,2,3,4,5,6,7,8,9}

after the return statement no more code is executed

没错。但是 ++ 不是 return 语句之后,它是 的一部分 .

您的代码等同于:

int temp = array[0];
array[0] = temp + 1;
return temp;

数组[0]++包含在return语句中。 因此,增加的值存储在数组 [0] 中(即数组 [0] = 1) 不要误以为 increment 会在 return 语句之后进行,因为它是 post-increment