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.
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.
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.
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.
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).
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With