Reputation: 25
I'm getting weird problems in my android app and I think it may be linked to the behavior of the way the ArrayList works. Check the following code and please tell me if I'm correct or doing something wrong:
ArrayList<ArrayList<String>> arr = new ArrayList<ArrayList<String>>();
ArrayList<String> tmp = new ArrayList<String>();
tmp.add("test");
arr.add(tmp);
tmp.clear();
After the last line the contents of arr[0] is emptied. So does that mean that when adding one ArrayList to another it does it by reference?
So if I have the following method:
void addArray(ArrayList<String> arr) {
group.add(arr); // group is ArrayList<ArrayList<String>>;
};
I must change it to:
void addArray(ArrayList<String> arr) {
ArrayList<String> tmp = new ArrayList<String>();
tmp.addAll(arr);
group.add(tmp); // group is ArrayList<ArrayList<String>>;
};
to make sure that if I clear the incoming array somewhere else that nothing happens to the group array?
Upvotes: 0
Views: 269
Reputation: 40193
In Java there is no passing by value, every object is passed by reference. So in your case arr[0]
and tmp
are the same object and clearing it will result in arr[0]
being cleared. Hope this helps.
EDIT
As a quick answer to the second part of your question: you don't need to use the tmp
ArrayList
inside the addArray
method. The argument of the addArray
method is a reference to the object, passed by value. So changing it won't have any effect outside of the addArray
method. Hope it's clear.
Upvotes: 3
Reputation: 83846
For objects Java always passes a copy of the reference value, so yes, the ArrayList you are clearing is the same as the one you added to the other ArrayList.
Upvotes: 0
Reputation: 272467
Yes, objects are not cloned when they're added to a collection.
Upvotes: 0