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?
In Java there is no passing by value, every object is passed by reference. So in your case
arr[0]andtmpare the same object and clearing it will result inarr[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
tmpArrayListinside theaddArraymethod. The argument of theaddArraymethod is a reference to the object, passed by value. So changing it won’t have any effect outside of theaddArraymethod. Hope it’s clear.