0

我有一个递归函数,它需要创建一个由特殊对象组成的数组......

我的自定义对象是从此类填充的:

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]

如何防止这种情况并使其发挥作用?问题出在哪里?任何帮助表示赞赏。谢谢...

4

2 回答 2

1

我暂时指定它不要更改递归函数的原始函数

你有 C/C++ 背景吗?

A = B

不在java中制作副本。它们都将指向同一个对象。这有点像所有变量都只是 C 指针。

您应该使用复制构造函数来制作列表的副本。

ArrayList<Integer> pos = new ArrayList<Integer>(positions);
于 2013-01-16T07:43:30.517 回答
1

您可以认为这ArrayList<Integer> pos = positions;就像您将指针分配给ArrayList(在 C/C++ 世界中),这意味着您将修改函数内的原始列表。要在本地列表上工作,您必须创建新列表并使用它:

ArrayLis<Integer> copiedList = new ArrayList<Integer>(ooriginalList);
于 2013-01-16T07:49:21.410 回答