This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center
                            
                        
                    
                
                6年前关闭。
            
        

我正在审核一个练习问题,我只想知道程序如何给出---> 2 1的答案的顺序。
我主要在理解主要驾驶员电话方面遇到困难。我了解这些方法的用法。

代码是:

public class Test {
  public static void main(String[] args) {
    int[] x = {1, 2, 3, 4, 5};
    increase(x);

    int[] y = {1, 2, 3, 4, 5};
    increase(y[0]);
    System.out.println(x[0] + " " + y[0]);
  }
  public static void increase(int[] x) {
    for (int i = 0; i < x.length; i++)
      x[i]++;
  }
  public static void increase(int y) {
     y++;
  }
}

最佳答案

该代码演示了(有效)按引用调用(在第一种增加方法中)和按值调用(在第二种增加方法中)之间的区别。实际上,这两种方法都使用按值调用,但是在第一种情况下,值是对对象(数组)的引用,在第二种情况下,值是int(数组中的单个值)。

代码int[] x = {1, 2, 3, 4, 5}创建一个数组。当您调用gain(x)时,您正在调用第一个增加方法。该方法迭代数组的元素并递增每个元素。 x[i]++行与x[i] = x[i] + 1等效。结果存储回数组。在此调用结束时,数组现在包含{2, 3, 4, 5, 6}。因此x[0]2

在第二次调用increase(int y)时,我们不传递数组,而是传递y[0]的值(即1)。该方法使变量y递增,但在方法外部无效。在Java中,当您传递变量时,变量将通过值传递,这实际上意味着将传递值的副本。对该值进行的任何更改均不会影响原始值。

传递数组时,将传递对数组对象的引用。引用不能更改,但是对象的内容(数组的内容)可以更改。

我不得不承认这有点令人困惑,但请重新阅读我几次写的内容,希望您能理解!

09-30 15:37
查看更多