Java推送到队列引用或值

时间:2013-12-05 12:46:51

标签: java queue

鉴于我在Java中尝试实现的规模较小:

int[][] arr = new int[2][2]{ 
    { 1, 0 },
    { 0, 1 }
};
int[][] path = null;

Queue<int[][]> q = new LinkedList<int[][]>();
q.add(arr);

while(q.size() != 0) {
    path = q.poll();    // pop the queue

    for (int i=0; i<2; i++) {
        for (int j=0; j<2; j++) {
            if (path[i][j] == 0) {
                path[i][j] = 1;
                q.add(path);
                path[i][j] = 0;
            }
        }
    }
}

我通过NetBeans跟踪了while和for循环中每次迭代的 q 的内容。然而,它们具有相同的价值。

我期待第一次for循环执行:

  

{{1,1},{0,1}}和{{1,0},{1,1}}

但相反,它们是:

  

{{1,0},{0,1}}和{{1,0},{0,1}}

这是数组 path 的最后一个值,因为嵌套for循环的第一次执行已经结束。

我应该怎样做才能使我推送到q的那个不是 path 数组的引用?

1 个答案:

答案 0 :(得分:1)

尝试添加path数组的副本。

for (int i=0; i<2; i++) {
    for (int j=0; j<2; j++) {
        if (path[i][j] == 0) {
            path[i][j] = 1;

            // here
            int[][] copy = new int[2][2];
            for(int k=0; k<2; k++) {
                copy[k] = path[k].clone();
            }

            q.add(copy);

            path[i][j] = 0; // now, this does not affect the added element
        }
    }
}

编辑:您无法克隆path变量,因为数组的第一级有引用。