Pregunta

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++)
{
  temp1=valuex.get(i);        
  VALUE.add(temp1);
}

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

clone();

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

¿Fue útil?

Solución

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
  newList.add(newFoo);
}

Otros consejos

When you passed a copy of the list to your three methods, you passed a reference to a copy of the list as a data structure. However, both lists, in memory, ended up pointing to the very same objects.

If your methods are changing the actual objects that the lists are pointing to, and you'd like to avoid that, then cloning the list is not enough: you must clone each and every object in the list as well.

By the way: the reason that clone() didn't work for you is that clone() only performs a shallow clone of the list: it creates a brand new ArrayList instance in memory, however the list's constituents are still the same objects (in memory) as the objects pointed-to by the original list.

You can just create a new ArrayList based on your existing arrayList before passing it in as argument.

List existingList = new ArrayList();
o1.m1(new ArrayList(existingList));
o2.m2(new ArrayList(existingList));
o3.m3(new ArrayList(existingList));

ArrayList contructor allows you to create a new ArrayList based on an existing collection. http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#ArrayList(java.util.Collection)

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top