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

Pretty explanatory: I need to change the ArrayList that I get, but I want the original not to change.

I know this is very simple, and I'm not sure why I do not know the final answer. I think it's better late than never.

+4
source share
4 answers

You will have a link to the original ArrayList .

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

See this question if you want a deep copy.

+4
source

Everything in java will be the default link. So yes, changing the returned arraylist will change the original one.

To prevent this problem, you need to create a copy of the original. To do this, use the .clone () method.

+2
source

If you want to change the list, but not change the original, you should not work on the list that you received in the method arguments, because you are working with a link. 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 } 
+2
source

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

0
source

Source: https://habr.com/ru/post/1340497/


All Articles