Don Corleone Don Corleone - 4 months ago 9x
Java Question

passing an ArrayList to a function makes changes in the original ArrayList

I need to pass the same ArrayList from the main function to 3 different functions (all in different classes).

When the 1st function receives the ArrayList, it makes changes not only in the local copy of the list but also the original ArrayList in the main method gets modified. This indicates that the changes are being made at the memory address.

So, in the first function I copied the received arraylist into another arraylist of the same type, using:

for(int i=0;i<valuex.size();i++)

This worked for the first time when I introduced this modification but then the same problem restored. Later I made three copies of the arraylist and passed each copy to each of the 3 functions. This too failed.

I didn't use


because this created the same problem some time back..
Please help...


You have described a shallow copy - you've made a fresh list, but you've got the same objects in each list.

If this isn't working for you, it suggests your method is modifying the list objects. To avoid this being a problem, you'll have to perform a deep copy - creating copies of each of your objects.

For example:

List<Foo> oldList = // ...
List<Foo> newList = new ArrayList<>();
for (Foo foo : oldList) {
  Foo newFoo = new Foo(foo); // copy constructor