在是否阵方法的变化? [英] Does array changes in method?

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

问题描述

当我写的是这样的:

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;

It prints 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 change the value? Or it changes values only for arrays?

推荐答案

在你的第一个例子中的 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天全站免登陆