Question

If a method returns an object from a particular array index, and then this object is modified, would this object only be modified locally or would the object in the array also be modified?

Is there a way to force each case?

Was it helpful?

Solution

The object in the array would also be modified. It works this way because, although Java is pass by value, it's passing the value of the object reference. So in the end the array has a copy of the reference and whatever gets the result has a copy of the reference. When you modify the object itself, you're modifying the thing that they both "point" to. So both see the change.

The only way to make this not true is to make a copy of the element before you return it.

Alternatively, if you make your object immutable, you don't have to worry about these details because you can't change the object in the first place.

OTHER TIPS

You need to make a defensive copy of the object if you want it to not be modified

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top