我有一個需要創建一個數組包含特殊對象的遞歸函數...遞歸函數更改原始數組?
我的自定義對象從該類填充:
public class CategoryItem {
boolean hasSubCategories = false;
ArrayList<CategoryItem> subs;
ArrayList<Integer> positions;
String categoryName, categoryId;
// They have setter and getter methods
}
這裏是我的遞歸函數:
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;
}
在此功能中,RandomBool()方法返回真/假隨機......而RandomId()也並不重要......
問題出在「位置」數組上。我想有每個項目有特定的位置陣列,諸如:
用於第一步驟中,每一個項目都需要有: [0],[1],[2],[3] ...
用於下一步驟中,讓我們假設我們選擇位於3: [3,0],[3,1],[3,2]
但是我發現,當我將項目添加到POS陣列我暫時不會改變遞歸函數中的原始函數,它也被添加到位置數組,即原始數組。因此,第一步的結果如下:每個項目上的 [0,1,2,3]。
和日誌就像:
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]
如何防止這一點,並使其發揮作用?哪裏有問題? 任何幫助表示讚賞。謝謝...
我也試過:ArrayList的 POS =(ArrayList的)positions.clone();但它也沒有幫助...那麼該怎麼做? –
yahya
@yahya嘗試複製構造函數,因爲我已經顯示 –
愚蠢的錯誤:)非常感謝你...我會在幾分鐘內接受你的答案... – yahya