I've got a recursive functions which needs to create an array consists of special objects...
My custom object is populated from this class:
public class CategoryItem {
boolean hasSubCategories = false;
ArrayList<CategoryItem> subs;
ArrayList<Integer> positions;
String categoryName, categoryId;
// They have setter and getter methods
}
And here is my recursive function:
public ArrayList<CategoryItem> GetLists(ArrayList<Integer> positions, int to) {
ArrayList<CategoryItem> items = new ArrayList<CategoryItem>();
for(int i = 0; i < to; i++) {
CategoryItem item = new CategoryItem();
item.setHasSubCategories(RandomBool());
item.setCategoryName("Category " + i);
item.setCategoryId(RandomId());
ArrayList<Integer> pos = positions;
pos.add(i);
Log.d(LOG, "positions: " + positions);
Log.d(LOG, "pos: " + pos);
item.setPositions(pos);
if(item.isHasSubCategories()) {
item.setSubs(GetLists(item.getPositions(), i));
}
items.add(item);
}
return items;
}
In this function, RandomBool() method returns true/false randomly... And RandomId() is also not important...
The problem is on "positions" array. I want to have every item has specific positions array, such as:
for the first step, every item needs to have: [0], [1], [2], [3] ...
for the next step, lets assume we picked positioned 3: [3,0], [3,1], [3,2]
But i found out that when i add an item to pos array, which i assigned it temporarly not to change the original one on recursive functions, it's been also added to positions array, the original one. So the result for the first step is like: [0,1,2,3] on every item.
And the log was like:
positions: []
pos: []
positions: [0]
pos: [0]
positions: [0, 1]
pos: [0, 1]
positions: [0, 1, 2]
pos: [0, 1, 2]
positions: [0, 1, 2, 0]
pos: [0, 1, 2, 0]
positions: [0, 1, 2, 0, 1]
pos: [0, 1, 2, 0, 1]
How to prevent this and make it work? Where is the problem? Any help is appreciated. Thanks...