问题
Are arrays in java pass by reference or pass by value? (I've similar questions asked before, but none of them seemed to get a good answer, so hopefully this time will be different).
Suppose I have an array called data
that contains Objects of some type. Now let us suppose that I pass and store that array in class A and then I pass it to class B and class B changes one of the entries of the array. Will class A's version of the array change? Does it matter if this was an array of primitives (such as int
) instead? What about ArrayLists?
Thanks
回答1:
Everything in Java is pass-by-value. However, if you're passing a reference, it's the value of the reference.
Since Java methods can't reach into the caller's stack to reassign variables, no method call can change the identity of a reference (address) there. This is what we mean when we say Java is not pass-by-reference. This contrasts with C++ (and similar languages), which allows this in some cases.
Now let's look at some effects.
If I do:
Object[] o = ...
mutateArray(o);
the contents can be different afterwards, since all mutateArray
needs is the address of an array to change its contents. However, the address of o
will be the same. If I do:
String x = "foo";
tryToMutateString(x);
the address of x
is again the same afterwards. Since strings are immutable, this implies that it will also still be "foo"
.
To mutate an object is to change the contents of it (e.g. successfully changing the last element of o
, or trying to change the last letter of "foo" to 'd'). This should not be be confused with reassigning x
or o
in the caller's stack (impossible).
The Wikipedia section on call by sharing may shed additional light.
回答2:
Arrays, like all other objects, are pass by reference (technically, you are passing a reference by value, but from the objects point of view, it is passed by reference). If you pass an array to a method and the method changes the array, the caller will see the changes. If you want to avoid having your copy modified, you need to copy it yourself. It doesn't matter whether the array contains primitives or objects. In general, this is the behavior you want, since passing by value would involve unnecessarily copying the (potentially large) array every time you use it as an argument.
回答3:
The Jist of it is - everything in Java is passed by reference, unless it is a primitive.
来源:https://stackoverflow.com/questions/9138691/are-arrays-in-java-pass-by-reference-or-pass-by-value