Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 want 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.

like image 617
efficiencyIsBliss Avatar asked Feb 20 '11 00:02

efficiencyIsBliss


People also ask

Does Java return by reference or value?

Java is always Pass by Value and not pass by reference, we can prove it with a simple example. Let's say we have a class Balloon like below.

Is list passed by reference in Java?

Yes, a List that you pass to a method is passed by reference. Any objects you add to the List inside the method will still be in the List after the method returns.

Can you return lists in Java?

The list() method of java. util. Collections class is used to return an array list containing the elements returned by the specified enumeration in the order they are returned by the enumeration. This method provides interoperability between legacy APIs that return enumerations and new APIs that require collections.

What does returning a value in Java mean?

A return statement causes the program control to transfer back to the caller of a method. Every method in Java is declared with a return type and it is mandatory for all java methods. A return type may be a primitive type like int, float, double, a reference type or void type(returns nothing).


2 Answers

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.

like image 98
Felix Kling Avatar answered Sep 18 '22 23:09

Felix Kling


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.

like image 38
Foxfire Avatar answered Sep 21 '22 23:09

Foxfire