I have an ArrayList:
ArrayList ReceivedPackets = new ArrayList();
And I have another ArrayList:
ArrayList returnList = ReceivedPackets;
Why does returnList loose it's value when I run this code?
ArrayList ReceivedPackets = new ArrayList(); // ReceivedPackets is empty
ReceivedPackets.Add(1); // Now it has an Integer
ArrayList returnList = ReceivedPackets; // Call-by-Reference (I thought), returnList now has an Integer
ReceivedPackets.clear(); // returnList is empty now. Why?
When you do this:
ArrayList returnList = ReceivedPackets;
You are creating a new variable called returnList
, but this variable points to the same in-memory object as ReceivedPackets
. There is still only one actual ArrayList
, it just has two variables pointing to it. So changes made to one are reflected in both.
How can I do without returnList loosing it's value?
Create a new object. At its simplest, that would look like this:
ArrayList returnList = new ArrayList();
If you also want that object to contain all the values from ReceivedPackets
, fortunately ArrayList
has a constructor overload which does just that:
ArrayList returnList = new ArrayList(ReceivedPackets);
Now you'd have two objects which should contain copies of the same data. Changes to one would not be reflected in the other.
In the absence of that constructor, ArrayList
also has some CopyTo()
methods which can be used to copy elements from one to the other. Failing that, you could also manually loop over the source ArrayList
and copy elements to the destination ArrayList
.
It's possible that this can get pretty confusing if the ArrayList
itself contains reference objects. Because those too may have multiple "pointers" to the same in-memory object.
For example, if you create a single Widget
object and add it to two ArrayList
objects, then any modifications made to the ArrayList
objects (adding/removing elements) would be independent, but any modification made to the Widget
object would be reflected in both ArrayList
s.
The point is that the ArrayList
itself is an object, independent of the objects it contains.
So, depending on the full context of what you're doing, your mileage may vary.