更改方法中的变量值,Java [英] Changing the values of variables in methods, Java

查看:97
本文介绍了更改方法中的变量值,Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于在Java中更改方法中变量值的问题。

I have a question about changing the values of variables in methods in Java.

这是我的代码:

public class Test {
    public static void funk(int a, int[] b) { 
        b[0] = b[0] * 2; 
        a = b[0] + 5;
    } 

    public static void main(String[] args) {
        int bird = 10;
        int[] tiger = {7};

        Test.funk(bird, tiger);
    }
}

执行方法 Test.funk(bird,tiger),bird的值没有改变 - 它仍然保留值 10 ,即使在 funk()方法我们用更改了值a = b [0] + 5;

After the execution of the method Test.funk(bird, tiger), the value of bird is not changed - it remains with the value 10, even though in the funk() method we have changed the value with a = b[0] + 5;

另一方面,数组中元素的值发生变化,因为我们有语句 b [0] = b [0] * 2;

On the other hand, the value of the element in the array changes, because we have the statement b[0] = b[0] * 2;

我不明白为什么有一件事发生变化而另一件事没有变化?有人可以帮我解释一下。

I don't understand why one thing changes and the other not? Could someone please explain this for me.

推荐答案

看看Jon Skeet关于参数传递用Java ,这解释了这一点。

Look at Jon Skeet's article about Parameter-Passing in Java, which explains this.

简而言之(请查看他的网站以获得更多解释):

In short (look at his site for a more throughout explanation):

数组是引用类型。如果传递指向数组的引用,则复制引用的值并将其分配给函数的参数。因此参数将指向与传递的参数相同的数组。因此,通过函数参数对数组所做的更改将在调用函数中可见。然而,更改参数本身(b),例如通过将其设置为 null ,调用函数将不会注意到,因为参数(b)只是参数的副本(tiger)传递。

Arrays are reference types. If you pass a reference that points to an array, the value of the reference is copied and assigned to the parameter of the function. So the parameter will point to the same array as the argument that was passed. Thus changes you make to the array through the parameter of your function will be visible in the calling function. Changing the parameter itself (b), for example by setting it to null, however, will not be noticed by the calling function, since the parameter (b) is just a copy of the argument (tiger) passed.

整数是所谓的原始类型。传递整数会复制其值并将其分配给参数。但该值不是对实际数据的引用,而是数据本身。因此,对函数中参数的更改将影响参数(a),但不会影响调用函数(bird)中传递的参数。

Integers are so-called primitive types. Passing the integer copies its value and assigns it to the parameter too. But that value is not a reference to the actual data, but is the data itself. So changes to the paramter in the function will affect the parameter (a), but not the argument passed in the calling function (bird).

这篇关于更改方法中的变量值,Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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