java 数组是否在方法中发生变化?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7127530/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 18:44:28  来源:igfitidea点击:

Does array changes in method?

javaarraysevaluation-strategy

提问by good_evening

When I write like this:

当我这样写时:

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;
    }
}

It prints x22;

它打印 x22;

When I write like this:

当我这样写时:

public class test {

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

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

It doesn't print x22, but prints x5.

它不打印 x22,但打印 x5。

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

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

回答by aioobe

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

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

Since Java passes everything by valuethe following will happen:

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

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

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

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

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

回答by Dan W

It's because your int is a primitive and the method smthcreates a local copy which is why it doesn't print the way you want. Objects are passed by value as well, but a value to the pointer in memory. So when it is changed, the pointer stays throughout both methods and you see the change. Read More Here

这是因为您的 int 是一个原始类型,并且该方法smth创建了一个本地副本,这就是为什么它不会以您想要的方式打印。对象也按值传递,但传递的是指向内存中指针的值。因此,当它更改时,指针将保留在两种方法中,您会看到更改。在这里阅读更多

回答by SipSop

Ok. An int in java ( and really all languages that have strict data typing ) is a primitive data type. Its just a single variable of that data type. In java this means its passed by value to the method. So when you pass in the argument, a copy of the passed variable is created. Any operations that take place in the method act on that copy not the passed variable.

行。java 中的 int(实际上所有具有严格数据类型的语言)是一种原始数据类型。它只是该数据类型的单个变量。在 java 中,这意味着它按值传递给方法。因此,当您传入参数时,会创建所传递变量的副本。方法中发生的任何操作都作用于该副本而不是传递的变量。

Actually in java EVERYTHING is passed by value but getting into the details of how that actually is true with what I am going to say next seems inadvisable.

实际上,在 Java 中,一切都是按值传递的,但详细了解我接下来要说的内容的真实性似乎是不可取的。

With the array...its a collection of variables of the primitive data type int. So an entire copy of the array isn't actually made just a copy of the reference to the memory that stores the array. so yes the value of the int IN the array is changed from operations in the method.

使用数组...它是原始数据类型 int 变量的集合。因此,数组的整个副本实际上并不只是对存储数组的内存的引用的副本。所以是的,数组中的 int 值是从方法中的操作中改变的。

In short methods don't change the external value of primitives (int,float,double,long,char) with the operations in the method, you have to return the resulting value of those operations to the caller if you wish to obtain it. Operations do change the value with most objects as well as with arrays of primitives. Hope that helps. Really unsure of how low level to get. Maybe someone else can clearly explain exactly why its by value. I "get" it but find it hard to help other people understand.

简而言之,方法不会通过方法中的操作更改基元(int、float、double、long、char)的外部值,如果您希望获得它,则必须将这些操作的结果值返回给调用者。操作确实会更改大多数对象以及基元数组的值。希望有帮助。真的不确定要获得多低的水平。也许其他人可以清楚地解释为什么它的价值。我“明白”了,但发现很难帮助其他人理解。

回答by Bhaskar

Think it in terms of memory: Lets analyse your first program -

从内存的角度考虑:让我们分析您的第一个程序 -

In mainx, fyeahis an array of ints , so its a reference ( or a pointer if I may ). This reference points to a location in heap memory where the actual array of ints is stored. Lets say at address 100. Located contiguously from here are three ints ( lets say beginning at address 100 , 104 and 108 respectively are 2 ,3 and 4 ).

In mainx,fyeah是一个ints数组,所以它是一个引用(如果可以的话,也可以是一个指针)。此引用指向堆内存中存储实际ints数组的位置。让我们说在地址 100 处。从这里开始连续放置三个整数(假设从地址 100 开始,104 和 108 分别是 2 ,3 和 4 )。

Now you call your method smthand pass the reference. Within the method , there is another reference ( of an intarray type ) named fyeah. This fyeahis quite distinct from fyeahreference in the mainxmethod. Now , when you call smthand pass the fyeahfrom mainx, the fyeahwithin the smthmethod is initialized to point to the same location ( ie memory address 100 ) When you access the 0 element of fyeahand assign it a value of 22 , it reaches out to the memory location of 100 and writes this value 22 there. When you come back in your mainxmethod , the fyeahreference is still referring to memory address 100. But the value present at that location is now 22. So you get that value when you access the first element from fyeahin mainx.

现在您调用您的方法smth并传递引用。在该方法中,还有另一个int名为 的引用(数组类型)fyeah。这与方法中的参考fyeah完全不同。现在,当您调用并传递from 时,方法内的初始化为指向同一位置(即内存地址 100) 当您访问 的 0 元素并为其分配值 22 时,它会到达内存位置100 并将此值 22 写入那里。当您返回您的方法时,fyeahmainxsmthfyeahmainxfyeahsmthfyeahmainxfyeah引用仍然指的是内存地址 100。但该位置的值现在是 22。因此,当您访问fyeahin 中的第一个元素时,您将获得该值mainx

Now , your second program. Your mainxmethod declares an int( not an array , but a simple int) and set it to 5. This fyeahvariable is created on stack not on the heap. The value of 5 is stored on the stack. Now you call smthand pass this variable. Within the method smth, you again declare an intvariable , fyeahby name ( as a formal method argument ). Again this is distinct from the fyeahof the mainxmethod and this fyeahis also created on stack.This variable will be initialized to a value of 5, copied over from the fyeahyou passed to smthas argument. Note now that there are two distinct copies on fyeahvariables , both on stack , and both a value of 5. Now you assign the fyeahin smtha value of 22. This will not affect the fyeahof the mainxmethod,so when you return to mainxand access fyeah, you see 5.

现在,你的第二个程序。您的mainx方法声明了一个int(不是数组,而是一个简单的int)并将其设置为 5。这个fyeah变量是在堆栈上而不是在堆上创建的。值 5 存储在堆栈中。现在你调用smth并传递这个变量。在该方法中smth,您再次按名称(作为正式方法参数)声明一个int变量fyeah。同样,这fyeahmainx方法的 不同,这fyeah也是在堆栈上创建的。此变量将被初始化为值 5,从作为参数fyeah传递给的复制过来smth。请注意,现在有两个不同的fyeah变量副本,都在堆栈上,并且都为 5。现在您分配fyeahinsmth22.这是一个值不会影响fyeah该的mainx当您返回到方法,所以mainx和访问fyeah,你看5。

回答by user85421

Seeing it a bit less technically, I would say that

从技术上看它有点少,我会说

    fyeah[0] = 22;

is changing the content of (the object pointed to by) fyeah, while

正在更改(指向的对象)fyeah 的内容,而

    fyeah = 22;

is changing (the variable) fyeah itself.
Another example:

正在改变(变量)fyeah 本身。
另一个例子:

void smth(Person person) {
    person.setAge(22);
}

is changing (the content of) the person while

正在改变人的(内容),而

void smth(Person person) {
    person = otherPerson;
}

is changing the variable person - the original instance of Person is still unchanged (and, since Java is pass-by-value, the variable in the calling code is not changed by this method)

正在更改变量 person - Person 的原始实例仍然保持不变(并且,由于 Java 是按值传递的,因此此方法不会更改调用代码中的变量)

回答by Joe

The intis a value type so 5 is passed directly into smthwhich can only modify the local copy. An array on the other hand is a reference type so the elements of that array can be modified.

int是一个值类型,所以直接传入 5smth只能修改本地副本。另一方面,数组是引用类型,因此可以修改该数组的元素。