数组是否在方法中发生变化? [英] Does array changes in method?

查看:34
本文介绍了数组是否在方法中发生变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我这样写时:

public class test {

    void mainx()
    {
        int fyeah[] = {2, 3, 4};
        smth(fyeah);
        System.out.println("x"+fyeah[0]);
    }

    void smth(int[] fyeah)
    {
        fyeah[0] = 22;
    }
}

它打印 x22;

当我这样写时:

public class test {

    void mainx()
    {
        int fyeah = 5;
        smth(fyeah);
        System.out.println("x"+fyeah);
    }

    void smth(int fyeah)
    {
        fyeah = 22;
    }
}

它不打印 x22,但打印 x5.

It doesn't print x22, but prints x5.

为什么在第二个版本函数中,值没有改变?它是否仅更改数组元素的值?

Why, in the second version function, doesn't the value change? Does it change values only for array elements?

推荐答案

第一个示例中的 fyeah 变量包含对数组的引用(不是数组),而第二个示例中的 fyeah 整数包含整数.

The fyeah variable in your first example contains a reference to an array (not an array), while the fyeah integer in your second example contains an integer.

由于 Java按值传递所有内容,因此将发生以下情况:

Since Java passes everything by value the following will happen:

在数组情况下:将发送数组引用的副本,并更改​​原始数组.

In the array case: A copy of the array reference will be sent, and the original array will be changed.

在 int 情况下:整数的副本将被更改,而原始整数不会被更改.

In the int case: A copy of the integer will be changed, and the original integer will not be changed.

这篇关于数组是否在方法中发生变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆