开发者

If I return a List in Java, is the return value a reference or the actual value?

Pretty self explanatory: I need to modify the ArrayList that I receive, but I wan开发者_开发知识库t the original to be unchanged.

I know this is very basic, and I'm not sure why I don't know the definitive answer. I guess better late than never though.


You will have a reference to the original ArrayList.

You can create a shallow copy of the list with clone().

Have a look at this question if you want a deep copy.


Everything in java will be a reference by default. So yes changing the returned arraylist will modify the original one.

To prevent that problem you have to create a copy of the original one. Use the .clone() method for that.


If you want a modified list, but not to modify the original, you shouldn't operate on the list which you received in arguments of the method because you operate on reference. Better use something like this:

public void modifyList(List myList) {
    myList.add("aaa"); // original *will* be modified
    List modifiable = new ArrayList(myList);
    modifiable.add("bbb"); // original will *not* be modified - only the copy
}


It will be the same ArrayList. If you want a copy, you'll have to copy it yourself. Not necessarily easy if the ArrayList holds complex objects!


I think java is pass-by-value always.

The only thing to remember is that objects are passed by passing the value of their address, or reference to them, this makes it seem as if they are passed by reference in C++ terms. Because essentially, you are passing the reference address not a copy of the object. The address is passed by value.

Thus, Java can say it is always passed by value because even when it is passing an object, it is only passing the value of its memory reference on the heap stack, not a clone/copy of the target object.

An Arraylist is an object, therefore it will be passed by value, so the value passed in will be a reference to the original Arraylist on the heap. Any modification to the Arraylist in your function, will modify the original on the heap.

I have not used the .clone(). I leave that to others to help with. Meanwhile, I will go learn about them myself.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜